ctl_frontend_iscsi.c revision 273319
1178354Ssam/*-
2178354Ssam * Copyright (c) 2012 The FreeBSD Foundation
3178354Ssam * All rights reserved.
4178354Ssam *
5178354Ssam * This software was developed by Edward Tomasz Napierala under sponsorship
6178354Ssam * from the FreeBSD Foundation.
7178354Ssam *
8178354Ssam * Redistribution and use in source and binary forms, with or without
9178354Ssam * modification, are permitted provided that the following conditions
10178354Ssam * are met:
11178354Ssam * 1. Redistributions of source code must retain the above copyright
12178354Ssam *    notice, this list of conditions and the following disclaimer.
13178354Ssam * 2. Redistributions in binary form must reproduce the above copyright
14178354Ssam *    notice, this list of conditions and the following disclaimer in the
15178354Ssam *    documentation and/or other materials provided with the distribution.
16178354Ssam *
17178354Ssam * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18178354Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19178354Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20178354Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21178354Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22178354Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23178354Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24178354Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25178354Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26178354Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27178354Ssam * SUCH DAMAGE.
28178354Ssam *
29178354Ssam * $FreeBSD: stable/10/sys/cam/ctl/ctl_frontend_iscsi.c 273319 2014-10-20 07:59:29Z mav $
30178354Ssam */
31178354Ssam
32178354Ssam/*
33178354Ssam * CTL frontend for the iSCSI protocol.
34178354Ssam */
35178354Ssam
36244060Sadrian#include <sys/cdefs.h>
37244060Sadrian__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl_frontend_iscsi.c 273319 2014-10-20 07:59:29Z mav $");
38244060Sadrian
39244060Sadrian#include <sys/param.h>
40244060Sadrian#include <sys/capability.h>
41244060Sadrian#include <sys/condvar.h>
42178354Ssam#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 = 3;
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;
1066
1067	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
1068	if (io == NULL) {
1069		CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io");
1070		return;
1071	}
1072	ctl_zero_io(io);
1073	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = cs;
1074	io->io_hdr.io_type = CTL_IO_TASK;
1075	io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
1076	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
1077	io->io_hdr.nexus.targ_target.id = 0;
1078	io->io_hdr.nexus.targ_lun = 0;
1079	io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
1080	io->taskio.task_action = CTL_TASK_I_T_NEXUS_RESET;
1081	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1082	error = ctl_queue(io);
1083	if (error != CTL_RETVAL_COMPLETE) {
1084		CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d", error);
1085		refcount_release(&cs->cs_outstanding_ctl_pdus);
1086		ctl_free_io(io);
1087	}
1088
1089	CFISCSI_SESSION_LOCK(cs);
1090	while ((cdw = TAILQ_FIRST(&cs->cs_waiting_for_data_out)) != NULL) {
1091		TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
1092		CFISCSI_SESSION_UNLOCK(cs);
1093		/*
1094		 * Set nonzero port status; this prevents backends from
1095		 * assuming that the data transfer actually succeeded
1096		 * and writing uninitialized data to disk.
1097		 */
1098		cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 42;
1099		cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
1100		uma_zfree(cfiscsi_data_wait_zone, cdw);
1101		CFISCSI_SESSION_LOCK(cs);
1102	}
1103	CFISCSI_SESSION_UNLOCK(cs);
1104
1105	/*
1106	 * Wait for CTL to terminate all the tasks.
1107	 */
1108	for (;;) {
1109		refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1110		last = refcount_release(&cs->cs_outstanding_ctl_pdus);
1111		if (last != 0)
1112			break;
1113		CFISCSI_SESSION_WARN(cs, "waiting for CTL to terminate tasks, "
1114		    "%d remaining", cs->cs_outstanding_ctl_pdus);
1115		tsleep(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus),
1116		    0, "cfiscsi_terminate", hz / 100);
1117	}
1118}
1119
1120static void
1121cfiscsi_maintenance_thread(void *arg)
1122{
1123	struct cfiscsi_session *cs;
1124
1125	cs = arg;
1126
1127	for (;;) {
1128		CFISCSI_SESSION_LOCK(cs);
1129		if (cs->cs_terminating == false)
1130			cv_wait(&cs->cs_maintenance_cv, &cs->cs_lock);
1131		CFISCSI_SESSION_UNLOCK(cs);
1132
1133		if (cs->cs_terminating) {
1134
1135			/*
1136			 * We used to wait up to 30 seconds to deliver queued
1137			 * PDUs to the initiator.  We also tried hard to deliver
1138			 * SCSI Responses for the aborted PDUs.  We don't do
1139			 * that anymore.  We might need to revisit that.
1140			 */
1141			callout_drain(&cs->cs_callout);
1142			icl_conn_close(cs->cs_conn);
1143
1144			/*
1145			 * At this point ICL receive thread is no longer
1146			 * running; no new tasks can be queued.
1147			 */
1148			cfiscsi_session_terminate_tasks(cs);
1149			cfiscsi_session_delete(cs);
1150			kthread_exit();
1151			return;
1152		}
1153		CFISCSI_SESSION_DEBUG(cs, "nothing to do");
1154	}
1155}
1156
1157static void
1158cfiscsi_session_terminate(struct cfiscsi_session *cs)
1159{
1160
1161	if (cs->cs_terminating)
1162		return;
1163	cs->cs_terminating = true;
1164	cv_signal(&cs->cs_maintenance_cv);
1165#ifdef ICL_KERNEL_PROXY
1166	cv_signal(&cs->cs_login_cv);
1167#endif
1168}
1169
1170static int
1171cfiscsi_session_register_initiator(struct cfiscsi_session *cs)
1172{
1173	struct cfiscsi_target *ct;
1174	char *name;
1175	int i;
1176
1177	KASSERT(cs->cs_ctl_initid == -1, ("already registered"));
1178
1179	ct = cs->cs_target;
1180	name = strdup(cs->cs_initiator_id, M_CTL);
1181	i = ctl_add_initiator(&ct->ct_port, -1, 0, name);
1182	if (i < 0) {
1183		CFISCSI_SESSION_WARN(cs, "ctl_add_initiator failed with error %d",
1184		    i);
1185		cs->cs_ctl_initid = -1;
1186		return (1);
1187	}
1188	cs->cs_ctl_initid = i;
1189#if 0
1190	CFISCSI_SESSION_DEBUG(cs, "added initiator id %d", i);
1191#endif
1192
1193	return (0);
1194}
1195
1196static void
1197cfiscsi_session_unregister_initiator(struct cfiscsi_session *cs)
1198{
1199	int error;
1200
1201	if (cs->cs_ctl_initid == -1)
1202		return;
1203
1204	error = ctl_remove_initiator(&cs->cs_target->ct_port, cs->cs_ctl_initid);
1205	if (error != 0) {
1206		CFISCSI_SESSION_WARN(cs, "ctl_remove_initiator failed with error %d",
1207		    error);
1208	}
1209	cs->cs_ctl_initid = -1;
1210}
1211
1212static struct cfiscsi_session *
1213cfiscsi_session_new(struct cfiscsi_softc *softc)
1214{
1215	struct cfiscsi_session *cs;
1216	int error;
1217
1218	cs = malloc(sizeof(*cs), M_CFISCSI, M_NOWAIT | M_ZERO);
1219	if (cs == NULL) {
1220		CFISCSI_WARN("malloc failed");
1221		return (NULL);
1222	}
1223	cs->cs_ctl_initid = -1;
1224
1225	refcount_init(&cs->cs_outstanding_ctl_pdus, 0);
1226	TAILQ_INIT(&cs->cs_waiting_for_data_out);
1227	mtx_init(&cs->cs_lock, "cfiscsi_lock", NULL, MTX_DEF);
1228	cv_init(&cs->cs_maintenance_cv, "cfiscsi_mt");
1229#ifdef ICL_KERNEL_PROXY
1230	cv_init(&cs->cs_login_cv, "cfiscsi_login");
1231#endif
1232
1233	cs->cs_conn = icl_conn_new("cfiscsi", &cs->cs_lock);
1234	cs->cs_conn->ic_receive = cfiscsi_receive_callback;
1235	cs->cs_conn->ic_error = cfiscsi_error_callback;
1236	cs->cs_conn->ic_prv0 = cs;
1237
1238	error = kthread_add(cfiscsi_maintenance_thread, cs, NULL, NULL, 0, 0, "cfiscsimt");
1239	if (error != 0) {
1240		CFISCSI_SESSION_WARN(cs, "kthread_add(9) failed with error %d", error);
1241		free(cs, M_CFISCSI);
1242		return (NULL);
1243	}
1244
1245	mtx_lock(&softc->lock);
1246	cs->cs_id = softc->last_session_id + 1;
1247	softc->last_session_id++;
1248	mtx_unlock(&softc->lock);
1249
1250	mtx_lock(&softc->lock);
1251	TAILQ_INSERT_TAIL(&softc->sessions, cs, cs_next);
1252	mtx_unlock(&softc->lock);
1253
1254	/*
1255	 * Start pinging the initiator.
1256	 */
1257	callout_init(&cs->cs_callout, 1);
1258	callout_reset(&cs->cs_callout, 1 * hz, cfiscsi_callout, cs);
1259
1260	return (cs);
1261}
1262
1263static void
1264cfiscsi_session_delete(struct cfiscsi_session *cs)
1265{
1266	struct cfiscsi_softc *softc;
1267
1268	softc = &cfiscsi_softc;
1269
1270	KASSERT(cs->cs_outstanding_ctl_pdus == 0,
1271	    ("destroying session with outstanding CTL pdus"));
1272	KASSERT(TAILQ_EMPTY(&cs->cs_waiting_for_data_out),
1273	    ("destroying session with non-empty queue"));
1274
1275	cfiscsi_session_unregister_initiator(cs);
1276	if (cs->cs_target != NULL)
1277		cfiscsi_target_release(cs->cs_target);
1278	icl_conn_close(cs->cs_conn);
1279	icl_conn_free(cs->cs_conn);
1280
1281	mtx_lock(&softc->lock);
1282	TAILQ_REMOVE(&softc->sessions, cs, cs_next);
1283	mtx_unlock(&softc->lock);
1284
1285	free(cs, M_CFISCSI);
1286}
1287
1288int
1289cfiscsi_init(void)
1290{
1291	struct cfiscsi_softc *softc;
1292	int retval;
1293
1294	softc = &cfiscsi_softc;
1295	retval = 0;
1296	bzero(softc, sizeof(*softc));
1297	mtx_init(&softc->lock, "cfiscsi", NULL, MTX_DEF);
1298
1299#ifdef ICL_KERNEL_PROXY
1300	cv_init(&softc->accept_cv, "cfiscsi_accept");
1301#endif
1302	TAILQ_INIT(&softc->sessions);
1303	TAILQ_INIT(&softc->targets);
1304
1305	cfiscsi_data_wait_zone = uma_zcreate("cfiscsi_data_wait",
1306	    sizeof(struct cfiscsi_data_wait), NULL, NULL, NULL, NULL,
1307	    UMA_ALIGN_PTR, 0);
1308
1309	return (0);
1310}
1311
1312#ifdef ICL_KERNEL_PROXY
1313static void
1314cfiscsi_accept(struct socket *so, struct sockaddr *sa, int portal_id)
1315{
1316	struct cfiscsi_session *cs;
1317
1318	cs = cfiscsi_session_new(&cfiscsi_softc);
1319	if (cs == NULL) {
1320		CFISCSI_WARN("failed to create session");
1321		return;
1322	}
1323
1324	icl_conn_handoff_sock(cs->cs_conn, so);
1325	cs->cs_initiator_sa = sa;
1326	cs->cs_portal_id = portal_id;
1327	cs->cs_waiting_for_ctld = true;
1328	cv_signal(&cfiscsi_softc.accept_cv);
1329}
1330#endif
1331
1332static void
1333cfiscsi_online(void *arg)
1334{
1335	struct cfiscsi_softc *softc;
1336	struct cfiscsi_target *ct;
1337	int online;
1338
1339	ct = (struct cfiscsi_target *)arg;
1340	softc = ct->ct_softc;
1341
1342	mtx_lock(&softc->lock);
1343	if (ct->ct_online) {
1344		mtx_unlock(&softc->lock);
1345		return;
1346	}
1347	ct->ct_online = 1;
1348	online = softc->online++;
1349	mtx_unlock(&softc->lock);
1350	if (online > 0)
1351		return;
1352
1353#ifdef ICL_KERNEL_PROXY
1354	if (softc->listener != NULL)
1355		icl_listen_free(softc->listener);
1356	softc->listener = icl_listen_new(cfiscsi_accept);
1357#endif
1358}
1359
1360static void
1361cfiscsi_offline(void *arg)
1362{
1363	struct cfiscsi_softc *softc;
1364	struct cfiscsi_target *ct;
1365	struct cfiscsi_session *cs;
1366	int online;
1367
1368	ct = (struct cfiscsi_target *)arg;
1369	softc = ct->ct_softc;
1370
1371	mtx_lock(&softc->lock);
1372	if (!ct->ct_online) {
1373		mtx_unlock(&softc->lock);
1374		return;
1375	}
1376	ct->ct_online = 0;
1377	online = --softc->online;
1378
1379	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1380		if (cs->cs_target == ct)
1381			cfiscsi_session_terminate(cs);
1382	}
1383	mtx_unlock(&softc->lock);
1384	if (online > 0)
1385		return;
1386
1387#ifdef ICL_KERNEL_PROXY
1388	icl_listen_free(softc->listener);
1389	softc->listener = NULL;
1390#endif
1391}
1392
1393static int
1394cfiscsi_info(void *arg, struct sbuf *sb)
1395{
1396	struct cfiscsi_target *ct = (struct cfiscsi_target *)arg;
1397	int retval;
1398
1399	retval = sbuf_printf(sb, "\t<cfiscsi_state>%d</cfiscsi_state>\n",
1400	    ct->ct_state);
1401	return (retval);
1402}
1403
1404static void
1405cfiscsi_ioctl_handoff(struct ctl_iscsi *ci)
1406{
1407	struct cfiscsi_softc *softc;
1408	struct cfiscsi_session *cs, *cs2;
1409	struct cfiscsi_target *ct;
1410	struct ctl_iscsi_handoff_params *cihp;
1411	int error;
1412
1413	cihp = (struct ctl_iscsi_handoff_params *)&(ci->data);
1414	softc = &cfiscsi_softc;
1415
1416	CFISCSI_DEBUG("new connection from %s (%s) to %s",
1417	    cihp->initiator_name, cihp->initiator_addr,
1418	    cihp->target_name);
1419
1420	ct = cfiscsi_target_find(softc, cihp->target_name);
1421	if (ct == NULL) {
1422		ci->status = CTL_ISCSI_ERROR;
1423		snprintf(ci->error_str, sizeof(ci->error_str),
1424		    "%s: target not found", __func__);
1425		return;
1426	}
1427
1428	if (ct->ct_online == 0) {
1429		ci->status = CTL_ISCSI_ERROR;
1430		snprintf(ci->error_str, sizeof(ci->error_str),
1431		    "%s: port offline", __func__);
1432		cfiscsi_target_release(ct);
1433		return;
1434	}
1435
1436#ifdef ICL_KERNEL_PROXY
1437	if (cihp->socket > 0 && cihp->connection_id > 0) {
1438		snprintf(ci->error_str, sizeof(ci->error_str),
1439		    "both socket and connection_id set");
1440		ci->status = CTL_ISCSI_ERROR;
1441		cfiscsi_target_release(ct);
1442		return;
1443	}
1444	if (cihp->socket == 0) {
1445		mtx_lock(&cfiscsi_softc.lock);
1446		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1447			if (cs->cs_id == cihp->socket)
1448				break;
1449		}
1450		if (cs == NULL) {
1451			mtx_unlock(&cfiscsi_softc.lock);
1452			snprintf(ci->error_str, sizeof(ci->error_str),
1453			    "connection not found");
1454			ci->status = CTL_ISCSI_ERROR;
1455			cfiscsi_target_release(ct);
1456			return;
1457		}
1458		mtx_unlock(&cfiscsi_softc.lock);
1459	} else {
1460#endif
1461		cs = cfiscsi_session_new(softc);
1462		if (cs == NULL) {
1463			ci->status = CTL_ISCSI_ERROR;
1464			snprintf(ci->error_str, sizeof(ci->error_str),
1465			    "%s: cfiscsi_session_new failed", __func__);
1466			cfiscsi_target_release(ct);
1467			return;
1468		}
1469#ifdef ICL_KERNEL_PROXY
1470	}
1471#endif
1472	cs->cs_target = ct;
1473
1474	/*
1475	 * First PDU of Full Feature phase has the same CmdSN as the last
1476	 * PDU from the Login Phase received from the initiator.  Thus,
1477	 * the -1 below.
1478	 */
1479	cs->cs_portal_group_tag = cihp->portal_group_tag;
1480	cs->cs_cmdsn = cihp->cmdsn;
1481	cs->cs_statsn = cihp->statsn;
1482	cs->cs_max_data_segment_length = cihp->max_recv_data_segment_length;
1483	cs->cs_max_burst_length = cihp->max_burst_length;
1484	cs->cs_immediate_data = !!cihp->immediate_data;
1485	if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1486		cs->cs_conn->ic_header_crc32c = true;
1487	if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1488		cs->cs_conn->ic_data_crc32c = true;
1489
1490	strlcpy(cs->cs_initiator_name,
1491	    cihp->initiator_name, sizeof(cs->cs_initiator_name));
1492	strlcpy(cs->cs_initiator_addr,
1493	    cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1494	strlcpy(cs->cs_initiator_alias,
1495	    cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1496	memcpy(cs->cs_initiator_isid,
1497	    cihp->initiator_isid, sizeof(cs->cs_initiator_isid));
1498	snprintf(cs->cs_initiator_id, sizeof(cs->cs_initiator_id),
1499	    "%s,i,0x%02x%02x%02x%02x%02x%02x", cs->cs_initiator_name,
1500	    cihp->initiator_isid[0], cihp->initiator_isid[1],
1501	    cihp->initiator_isid[2], cihp->initiator_isid[3],
1502	    cihp->initiator_isid[4], cihp->initiator_isid[5]);
1503
1504	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1505restart:
1506	if (!cs->cs_terminating) {
1507		mtx_lock(&softc->lock);
1508		TAILQ_FOREACH(cs2, &softc->sessions, cs_next) {
1509			if (cs2 != cs && cs2->cs_tasks_aborted == false &&
1510			    cs->cs_target == cs2->cs_target &&
1511			    cs->cs_portal_group_tag == cs2->cs_portal_group_tag &&
1512			    strcmp(cs->cs_initiator_id, cs2->cs_initiator_id) == 0) {
1513				cfiscsi_session_terminate(cs2);
1514				mtx_unlock(&softc->lock);
1515				pause("cfiscsi_reinstate", 1);
1516				goto restart;
1517			}
1518		}
1519		mtx_unlock(&softc->lock);
1520	}
1521
1522	/*
1523	 * Register initiator with CTL.
1524	 */
1525	cfiscsi_session_register_initiator(cs);
1526
1527#ifdef ICL_KERNEL_PROXY
1528	if (cihp->socket > 0) {
1529#endif
1530		error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1531		if (error != 0) {
1532			cfiscsi_session_terminate(cs);
1533			refcount_release(&cs->cs_outstanding_ctl_pdus);
1534			ci->status = CTL_ISCSI_ERROR;
1535			snprintf(ci->error_str, sizeof(ci->error_str),
1536			    "%s: icl_conn_handoff failed with error %d",
1537			    __func__, error);
1538			return;
1539		}
1540#ifdef ICL_KERNEL_PROXY
1541	}
1542#endif
1543
1544#ifdef ICL_KERNEL_PROXY
1545	cs->cs_login_phase = false;
1546
1547	/*
1548	 * First PDU of the Full Feature phase has likely already arrived.
1549	 * We have to pick it up and execute properly.
1550	 */
1551	if (cs->cs_login_pdu != NULL) {
1552		CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1553		cfiscsi_pdu_handle(cs->cs_login_pdu);
1554		cs->cs_login_pdu = NULL;
1555	}
1556#endif
1557
1558	refcount_release(&cs->cs_outstanding_ctl_pdus);
1559	ci->status = CTL_ISCSI_OK;
1560}
1561
1562static void
1563cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1564{
1565	struct ctl_iscsi_list_params *cilp;
1566	struct cfiscsi_session *cs;
1567	struct cfiscsi_softc *softc;
1568	struct sbuf *sb;
1569	int error;
1570
1571	cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1572	softc = &cfiscsi_softc;
1573
1574	sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1575	if (sb == NULL) {
1576		ci->status = CTL_ISCSI_ERROR;
1577		snprintf(ci->error_str, sizeof(ci->error_str),
1578		    "Unable to allocate %d bytes for iSCSI session list",
1579		    cilp->alloc_len);
1580		return;
1581	}
1582
1583	sbuf_printf(sb, "<ctlislist>\n");
1584	mtx_lock(&softc->lock);
1585	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1586#ifdef ICL_KERNEL_PROXY
1587		if (cs->cs_target == NULL)
1588			continue;
1589#endif
1590		error = sbuf_printf(sb, "<connection id=\"%d\">"
1591		    "<initiator>%s</initiator>"
1592		    "<initiator_addr>%s</initiator_addr>"
1593		    "<initiator_alias>%s</initiator_alias>"
1594		    "<target>%s</target>"
1595		    "<target_alias>%s</target_alias>"
1596		    "<header_digest>%s</header_digest>"
1597		    "<data_digest>%s</data_digest>"
1598		    "<max_data_segment_length>%zd</max_data_segment_length>"
1599		    "<immediate_data>%d</immediate_data>"
1600		    "<iser>%d</iser>"
1601		    "</connection>\n",
1602		    cs->cs_id,
1603		    cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1604		    cs->cs_target->ct_name, cs->cs_target->ct_alias,
1605		    cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1606		    cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1607		    cs->cs_max_data_segment_length,
1608		    cs->cs_immediate_data,
1609		    cs->cs_conn->ic_iser);
1610		if (error != 0)
1611			break;
1612	}
1613	mtx_unlock(&softc->lock);
1614	error = sbuf_printf(sb, "</ctlislist>\n");
1615	if (error != 0) {
1616		sbuf_delete(sb);
1617		ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1618		snprintf(ci->error_str, sizeof(ci->error_str),
1619		    "Out of space, %d bytes is too small", cilp->alloc_len);
1620		return;
1621	}
1622	sbuf_finish(sb);
1623
1624	error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1625	cilp->fill_len = sbuf_len(sb) + 1;
1626	ci->status = CTL_ISCSI_OK;
1627	sbuf_delete(sb);
1628}
1629
1630static void
1631cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1632{
1633	struct icl_pdu *response;
1634	struct iscsi_bhs_asynchronous_message *bhsam;
1635	struct ctl_iscsi_terminate_params *citp;
1636	struct cfiscsi_session *cs;
1637	struct cfiscsi_softc *softc;
1638	int found = 0;
1639
1640	citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1641	softc = &cfiscsi_softc;
1642
1643	mtx_lock(&softc->lock);
1644	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1645		if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1646		    strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1647		    strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1648			continue;
1649
1650		response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1651		if (response == NULL) {
1652			/*
1653			 * Oh well.  Just terminate the connection.
1654			 */
1655		} else {
1656			bhsam = (struct iscsi_bhs_asynchronous_message *)
1657			    response->ip_bhs;
1658			bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1659			bhsam->bhsam_flags = 0x80;
1660			bhsam->bhsam_0xffffffff = 0xffffffff;
1661			bhsam->bhsam_async_event =
1662			    BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1663			cfiscsi_pdu_queue(response);
1664		}
1665		cfiscsi_session_terminate(cs);
1666		found++;
1667	}
1668	mtx_unlock(&softc->lock);
1669
1670	if (found == 0) {
1671		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1672		snprintf(ci->error_str, sizeof(ci->error_str),
1673		    "No matching connections found");
1674		return;
1675	}
1676
1677	ci->status = CTL_ISCSI_OK;
1678}
1679
1680static void
1681cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1682{
1683	struct icl_pdu *response;
1684	struct iscsi_bhs_asynchronous_message *bhsam;
1685	struct ctl_iscsi_logout_params *cilp;
1686	struct cfiscsi_session *cs;
1687	struct cfiscsi_softc *softc;
1688	int found = 0;
1689
1690	cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1691	softc = &cfiscsi_softc;
1692
1693	mtx_lock(&softc->lock);
1694	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1695		if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1696		    strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1697		    strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1698			continue;
1699
1700		response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1701		if (response == NULL) {
1702			ci->status = CTL_ISCSI_ERROR;
1703			snprintf(ci->error_str, sizeof(ci->error_str),
1704			    "Unable to allocate memory");
1705			mtx_unlock(&softc->lock);
1706			return;
1707		}
1708		bhsam =
1709		    (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1710		bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1711		bhsam->bhsam_flags = 0x80;
1712		bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1713		bhsam->bhsam_parameter3 = htons(10);
1714		cfiscsi_pdu_queue(response);
1715		found++;
1716	}
1717	mtx_unlock(&softc->lock);
1718
1719	if (found == 0) {
1720		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1721		snprintf(ci->error_str, sizeof(ci->error_str),
1722		    "No matching connections found");
1723		return;
1724	}
1725
1726	ci->status = CTL_ISCSI_OK;
1727}
1728
1729#ifdef ICL_KERNEL_PROXY
1730static void
1731cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1732{
1733	struct ctl_iscsi_listen_params *cilp;
1734	struct sockaddr *sa;
1735	int error;
1736
1737	cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1738
1739	if (cfiscsi_softc.listener == NULL) {
1740		CFISCSI_DEBUG("no listener");
1741		snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1742		ci->status = CTL_ISCSI_ERROR;
1743		return;
1744	}
1745
1746	error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1747	if (error != 0) {
1748		CFISCSI_DEBUG("getsockaddr, error %d", error);
1749		snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1750		ci->status = CTL_ISCSI_ERROR;
1751		return;
1752	}
1753
1754	error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1755	    cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1756	if (error != 0) {
1757		free(sa, M_SONAME);
1758		CFISCSI_DEBUG("icl_listen_add, error %d", error);
1759		snprintf(ci->error_str, sizeof(ci->error_str),
1760		    "icl_listen_add failed, error %d", error);
1761		ci->status = CTL_ISCSI_ERROR;
1762		return;
1763	}
1764
1765	ci->status = CTL_ISCSI_OK;
1766}
1767
1768static void
1769cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1770{
1771	struct ctl_iscsi_accept_params *ciap;
1772	struct cfiscsi_session *cs;
1773	int error;
1774
1775	ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1776
1777	mtx_lock(&cfiscsi_softc.lock);
1778	for (;;) {
1779		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1780			if (cs->cs_waiting_for_ctld)
1781				break;
1782		}
1783		if (cs != NULL)
1784			break;
1785		error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1786		if (error != 0) {
1787			mtx_unlock(&cfiscsi_softc.lock);
1788			snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1789			ci->status = CTL_ISCSI_ERROR;
1790			return;
1791		}
1792	}
1793	mtx_unlock(&cfiscsi_softc.lock);
1794
1795	cs->cs_waiting_for_ctld = false;
1796	cs->cs_login_phase = true;
1797
1798	ciap->connection_id = cs->cs_id;
1799	ciap->portal_id = cs->cs_portal_id;
1800	ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1801	error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1802	    cs->cs_initiator_sa->sa_len);
1803	if (error != 0) {
1804		snprintf(ci->error_str, sizeof(ci->error_str),
1805		    "copyout failed with error %d", error);
1806		ci->status = CTL_ISCSI_ERROR;
1807		return;
1808	}
1809
1810	ci->status = CTL_ISCSI_OK;
1811}
1812
1813static void
1814cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1815{
1816	struct ctl_iscsi_send_params *cisp;
1817	struct cfiscsi_session *cs;
1818	struct icl_pdu *ip;
1819	size_t datalen;
1820	void *data;
1821	int error;
1822
1823	cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1824
1825	mtx_lock(&cfiscsi_softc.lock);
1826	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1827		if (cs->cs_id == cisp->connection_id)
1828			break;
1829	}
1830	if (cs == NULL) {
1831		mtx_unlock(&cfiscsi_softc.lock);
1832		snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1833		ci->status = CTL_ISCSI_ERROR;
1834		return;
1835	}
1836	mtx_unlock(&cfiscsi_softc.lock);
1837
1838#if 0
1839	if (cs->cs_login_phase == false)
1840		return (EBUSY);
1841#endif
1842
1843	if (cs->cs_terminating) {
1844		snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1845		ci->status = CTL_ISCSI_ERROR;
1846		return;
1847	}
1848
1849	datalen = cisp->data_segment_len;
1850	/*
1851	 * XXX
1852	 */
1853	//if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1854	if (datalen > 65535) {
1855		snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1856		ci->status = CTL_ISCSI_ERROR;
1857		return;
1858	}
1859	if (datalen > 0) {
1860		data = malloc(datalen, M_CFISCSI, M_WAITOK);
1861		error = copyin(cisp->data_segment, data, datalen);
1862		if (error != 0) {
1863			free(data, M_CFISCSI);
1864			snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1865			ci->status = CTL_ISCSI_ERROR;
1866			return;
1867		}
1868	}
1869
1870	ip = icl_pdu_new_bhs(cs->cs_conn, M_WAITOK);
1871	memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1872	if (datalen > 0) {
1873		icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1874		free(data, M_CFISCSI);
1875	}
1876	CFISCSI_SESSION_LOCK(cs);
1877	icl_pdu_queue(ip);
1878	CFISCSI_SESSION_UNLOCK(cs);
1879	ci->status = CTL_ISCSI_OK;
1880}
1881
1882static void
1883cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1884{
1885	struct ctl_iscsi_receive_params *cirp;
1886	struct cfiscsi_session *cs;
1887	struct icl_pdu *ip;
1888	void *data;
1889	int error;
1890
1891	cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1892
1893	mtx_lock(&cfiscsi_softc.lock);
1894	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1895		if (cs->cs_id == cirp->connection_id)
1896			break;
1897	}
1898	if (cs == NULL) {
1899		mtx_unlock(&cfiscsi_softc.lock);
1900		snprintf(ci->error_str, sizeof(ci->error_str),
1901		    "connection not found");
1902		ci->status = CTL_ISCSI_ERROR;
1903		return;
1904	}
1905	mtx_unlock(&cfiscsi_softc.lock);
1906
1907#if 0
1908	if (is->is_login_phase == false)
1909		return (EBUSY);
1910#endif
1911
1912	CFISCSI_SESSION_LOCK(cs);
1913	while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
1914		error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
1915		if (error != 0) {
1916			CFISCSI_SESSION_UNLOCK(cs);
1917			snprintf(ci->error_str, sizeof(ci->error_str),
1918			    "interrupted by signal");
1919			ci->status = CTL_ISCSI_ERROR;
1920			return;
1921		}
1922	}
1923
1924	if (cs->cs_terminating) {
1925		CFISCSI_SESSION_UNLOCK(cs);
1926		snprintf(ci->error_str, sizeof(ci->error_str),
1927		    "connection terminating");
1928		ci->status = CTL_ISCSI_ERROR;
1929		return;
1930	}
1931	ip = cs->cs_login_pdu;
1932	cs->cs_login_pdu = NULL;
1933	CFISCSI_SESSION_UNLOCK(cs);
1934
1935	if (ip->ip_data_len > cirp->data_segment_len) {
1936		icl_pdu_free(ip);
1937		snprintf(ci->error_str, sizeof(ci->error_str),
1938		    "data segment too big");
1939		ci->status = CTL_ISCSI_ERROR;
1940		return;
1941	}
1942
1943	copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
1944	if (ip->ip_data_len > 0) {
1945		data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
1946		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1947		copyout(data, cirp->data_segment, ip->ip_data_len);
1948		free(data, M_CFISCSI);
1949	}
1950
1951	icl_pdu_free(ip);
1952	ci->status = CTL_ISCSI_OK;
1953}
1954
1955#endif /* !ICL_KERNEL_PROXY */
1956
1957static void
1958cfiscsi_ioctl_port_create(struct ctl_req *req)
1959{
1960	struct cfiscsi_target *ct;
1961	struct ctl_port *port;
1962	const char *target, *alias, *tag;
1963	struct scsi_vpd_id_descriptor *desc;
1964	ctl_options_t opts;
1965	int retval, len, idlen;
1966
1967	ctl_init_opts(&opts, req->num_args, req->kern_args);
1968	target = ctl_get_opt(&opts, "cfiscsi_target");
1969	alias = ctl_get_opt(&opts, "cfiscsi_target_alias");
1970	tag = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
1971	if (target == NULL || tag == NULL) {
1972		req->status = CTL_LUN_ERROR;
1973		snprintf(req->error_str, sizeof(req->error_str),
1974		    "Missing required argument");
1975		ctl_free_opts(&opts);
1976		return;
1977	}
1978	ct = cfiscsi_target_find_or_create(&cfiscsi_softc, target, alias);
1979	if (ct == NULL) {
1980		req->status = CTL_LUN_ERROR;
1981		snprintf(req->error_str, sizeof(req->error_str),
1982		    "failed to create target \"%s\"", target);
1983		ctl_free_opts(&opts);
1984		return;
1985	}
1986	if (ct->ct_state == CFISCSI_TARGET_STATE_ACTIVE) {
1987		req->status = CTL_LUN_ERROR;
1988		snprintf(req->error_str, sizeof(req->error_str),
1989		    "target \"%s\" already exist", target);
1990		cfiscsi_target_release(ct);
1991		ctl_free_opts(&opts);
1992		return;
1993	}
1994	port = &ct->ct_port;
1995	if (ct->ct_state == CFISCSI_TARGET_STATE_DYING)
1996		goto done;
1997
1998	port->frontend = &cfiscsi_frontend;
1999	port->port_type = CTL_PORT_ISCSI;
2000	/* XXX KDM what should the real number be here? */
2001	port->num_requested_ctl_io = 4096;
2002	port->port_name = "iscsi";
2003	port->physical_port = strtoul(tag, NULL, 0);
2004	port->virtual_port = ct->ct_target_id;
2005	port->port_online = cfiscsi_online;
2006	port->port_offline = cfiscsi_offline;
2007	port->port_info = cfiscsi_info;
2008	port->onoff_arg = ct;
2009	port->lun_enable = cfiscsi_lun_enable;
2010	port->lun_disable = cfiscsi_lun_disable;
2011	port->lun_map = cfiscsi_lun_map;
2012	port->targ_lun_arg = ct;
2013	port->fe_datamove = cfiscsi_datamove;
2014	port->fe_done = cfiscsi_done;
2015
2016	/* XXX KDM what should we report here? */
2017	/* XXX These should probably be fetched from CTL. */
2018	port->max_targets = 1;
2019	port->max_target_id = 15;
2020
2021	port->options = opts;
2022	STAILQ_INIT(&opts);
2023
2024	/* Generate Port ID. */
2025	idlen = strlen(target) + strlen(",t,0x0001") + 1;
2026	idlen = roundup2(idlen, 4);
2027	len = sizeof(struct scsi_vpd_device_id) + idlen;
2028	port->port_devid = malloc(sizeof(struct ctl_devid) + len,
2029	    M_CTL, M_WAITOK | M_ZERO);
2030	port->port_devid->len = len;
2031	desc = (struct scsi_vpd_id_descriptor *)port->port_devid->data;
2032	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2033	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2034	    SVPD_ID_TYPE_SCSI_NAME;
2035	desc->length = idlen;
2036	snprintf(desc->identifier, idlen, "%s,t,0x%4.4x",
2037	    target, port->physical_port);
2038
2039	/* Generate Target ID. */
2040	idlen = strlen(target) + 1;
2041	idlen = roundup2(idlen, 4);
2042	len = sizeof(struct scsi_vpd_device_id) + idlen;
2043	port->target_devid = malloc(sizeof(struct ctl_devid) + len,
2044	    M_CTL, M_WAITOK | M_ZERO);
2045	port->target_devid->len = len;
2046	desc = (struct scsi_vpd_id_descriptor *)port->target_devid->data;
2047	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2048	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2049	    SVPD_ID_TYPE_SCSI_NAME;
2050	desc->length = idlen;
2051	strlcpy(desc->identifier, target, idlen);
2052
2053	retval = ctl_port_register(port, /*master_SC*/ 1);
2054	if (retval != 0) {
2055		ctl_free_opts(&port->options);
2056		cfiscsi_target_release(ct);
2057		free(port->port_devid, M_CFISCSI);
2058		free(port->target_devid, M_CFISCSI);
2059		req->status = CTL_LUN_ERROR;
2060		snprintf(req->error_str, sizeof(req->error_str),
2061		    "ctl_frontend_register() failed with error %d", retval);
2062		return;
2063	}
2064done:
2065	ct->ct_state = CFISCSI_TARGET_STATE_ACTIVE;
2066	req->status = CTL_LUN_OK;
2067	memcpy(req->kern_args[0].kvalue, &port->targ_port,
2068	    sizeof(port->targ_port)); //XXX
2069}
2070
2071static void
2072cfiscsi_ioctl_port_remove(struct ctl_req *req)
2073{
2074	struct cfiscsi_target *ct;
2075	const char *target;
2076	ctl_options_t opts;
2077
2078	ctl_init_opts(&opts, req->num_args, req->kern_args);
2079	target = ctl_get_opt(&opts, "cfiscsi_target");
2080	if (target == NULL) {
2081		ctl_free_opts(&opts);
2082		req->status = CTL_LUN_ERROR;
2083		snprintf(req->error_str, sizeof(req->error_str),
2084		    "Missing required argument");
2085		return;
2086	}
2087	ct = cfiscsi_target_find(&cfiscsi_softc, target);
2088	if (ct == NULL) {
2089		ctl_free_opts(&opts);
2090		req->status = CTL_LUN_ERROR;
2091		snprintf(req->error_str, sizeof(req->error_str),
2092		    "can't find target \"%s\"", target);
2093		return;
2094	}
2095	if (ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE) {
2096		ctl_free_opts(&opts);
2097		req->status = CTL_LUN_ERROR;
2098		snprintf(req->error_str, sizeof(req->error_str),
2099		    "target \"%s\" is already dying", target);
2100		return;
2101	}
2102	ctl_free_opts(&opts);
2103
2104	ct->ct_state = CFISCSI_TARGET_STATE_DYING;
2105	ctl_port_offline(&ct->ct_port);
2106	cfiscsi_target_release(ct);
2107	cfiscsi_target_release(ct);
2108}
2109
2110static int
2111cfiscsi_ioctl(struct cdev *dev,
2112    u_long cmd, caddr_t addr, int flag, struct thread *td)
2113{
2114	struct ctl_iscsi *ci;
2115	struct ctl_req *req;
2116
2117	if (cmd == CTL_PORT_REQ) {
2118		req = (struct ctl_req *)addr;
2119		switch (req->reqtype) {
2120		case CTL_REQ_CREATE:
2121			cfiscsi_ioctl_port_create(req);
2122			break;
2123		case CTL_REQ_REMOVE:
2124			cfiscsi_ioctl_port_remove(req);
2125			break;
2126		default:
2127			req->status = CTL_LUN_ERROR;
2128			snprintf(req->error_str, sizeof(req->error_str),
2129			    "Unsupported request type %d", req->reqtype);
2130		}
2131		return (0);
2132	}
2133
2134	if (cmd != CTL_ISCSI)
2135		return (ENOTTY);
2136
2137	ci = (struct ctl_iscsi *)addr;
2138	switch (ci->type) {
2139	case CTL_ISCSI_HANDOFF:
2140		cfiscsi_ioctl_handoff(ci);
2141		break;
2142	case CTL_ISCSI_LIST:
2143		cfiscsi_ioctl_list(ci);
2144		break;
2145	case CTL_ISCSI_TERMINATE:
2146		cfiscsi_ioctl_terminate(ci);
2147		break;
2148	case CTL_ISCSI_LOGOUT:
2149		cfiscsi_ioctl_logout(ci);
2150		break;
2151#ifdef ICL_KERNEL_PROXY
2152	case CTL_ISCSI_LISTEN:
2153		cfiscsi_ioctl_listen(ci);
2154		break;
2155	case CTL_ISCSI_ACCEPT:
2156		cfiscsi_ioctl_accept(ci);
2157		break;
2158	case CTL_ISCSI_SEND:
2159		cfiscsi_ioctl_send(ci);
2160		break;
2161	case CTL_ISCSI_RECEIVE:
2162		cfiscsi_ioctl_receive(ci);
2163		break;
2164#else
2165	case CTL_ISCSI_LISTEN:
2166	case CTL_ISCSI_ACCEPT:
2167	case CTL_ISCSI_SEND:
2168	case CTL_ISCSI_RECEIVE:
2169		ci->status = CTL_ISCSI_ERROR;
2170		snprintf(ci->error_str, sizeof(ci->error_str),
2171		    "%s: CTL compiled without ICL_KERNEL_PROXY",
2172		    __func__);
2173		break;
2174#endif /* !ICL_KERNEL_PROXY */
2175	default:
2176		ci->status = CTL_ISCSI_ERROR;
2177		snprintf(ci->error_str, sizeof(ci->error_str),
2178		    "%s: invalid iSCSI request type %d", __func__, ci->type);
2179		break;
2180	}
2181
2182	return (0);
2183}
2184
2185static void
2186cfiscsi_target_hold(struct cfiscsi_target *ct)
2187{
2188
2189	refcount_acquire(&ct->ct_refcount);
2190}
2191
2192static void
2193cfiscsi_target_release(struct cfiscsi_target *ct)
2194{
2195	struct cfiscsi_softc *softc;
2196
2197	softc = ct->ct_softc;
2198	mtx_lock(&softc->lock);
2199	if (refcount_release(&ct->ct_refcount)) {
2200		TAILQ_REMOVE(&softc->targets, ct, ct_next);
2201		mtx_unlock(&softc->lock);
2202		if (ct->ct_state != CFISCSI_TARGET_STATE_INVALID) {
2203			ct->ct_state = CFISCSI_TARGET_STATE_INVALID;
2204			if (ctl_port_deregister(&ct->ct_port) != 0)
2205				printf("%s: ctl_port_deregister() failed\n",
2206				    __func__);
2207		}
2208		free(ct, M_CFISCSI);
2209
2210		return;
2211	}
2212	mtx_unlock(&softc->lock);
2213}
2214
2215static struct cfiscsi_target *
2216cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name)
2217{
2218	struct cfiscsi_target *ct;
2219
2220	mtx_lock(&softc->lock);
2221	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2222		if (strcmp(name, ct->ct_name) != 0 ||
2223		    ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE)
2224			continue;
2225		cfiscsi_target_hold(ct);
2226		mtx_unlock(&softc->lock);
2227		return (ct);
2228	}
2229	mtx_unlock(&softc->lock);
2230
2231	return (NULL);
2232}
2233
2234static struct cfiscsi_target *
2235cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2236    const char *alias)
2237{
2238	struct cfiscsi_target *ct, *newct;
2239	int i;
2240
2241	if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2242		return (NULL);
2243
2244	newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2245
2246	mtx_lock(&softc->lock);
2247	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2248		if (strcmp(name, ct->ct_name) != 0 ||
2249		    ct->ct_state == CFISCSI_TARGET_STATE_INVALID)
2250			continue;
2251		cfiscsi_target_hold(ct);
2252		mtx_unlock(&softc->lock);
2253		free(newct, M_CFISCSI);
2254		return (ct);
2255	}
2256
2257	for (i = 0; i < CTL_MAX_LUNS; i++)
2258		newct->ct_luns[i] = UINT32_MAX;
2259
2260	strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2261	if (alias != NULL)
2262		strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2263	refcount_init(&newct->ct_refcount, 1);
2264	newct->ct_softc = softc;
2265	if (TAILQ_EMPTY(&softc->targets))
2266		softc->last_target_id = 0;
2267	newct->ct_target_id = ++softc->last_target_id;
2268	TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2269	mtx_unlock(&softc->lock);
2270
2271	return (newct);
2272}
2273
2274/*
2275 * Takes LUN from the target space and returns LUN from the CTL space.
2276 */
2277static uint32_t
2278cfiscsi_lun_map(void *arg, uint32_t lun)
2279{
2280	struct cfiscsi_target *ct = arg;
2281
2282	if (lun >= CTL_MAX_LUNS) {
2283		CFISCSI_DEBUG("requested lun number %d is higher "
2284		    "than maximum %d", lun, CTL_MAX_LUNS - 1);
2285		return (UINT32_MAX);
2286	}
2287	return (ct->ct_luns[lun]);
2288}
2289
2290static int
2291cfiscsi_target_set_lun(struct cfiscsi_target *ct,
2292    unsigned long lun_id, unsigned long ctl_lun_id)
2293{
2294
2295	if (lun_id >= CTL_MAX_LUNS) {
2296		CFISCSI_WARN("requested lun number %ld is higher "
2297		    "than maximum %d", lun_id, CTL_MAX_LUNS - 1);
2298		return (-1);
2299	}
2300
2301	if (ct->ct_luns[lun_id] < CTL_MAX_LUNS) {
2302		/*
2303		 * CTL calls cfiscsi_lun_enable() twice for each LUN - once
2304		 * when the LUN is created, and a second time just before
2305		 * the port is brought online; don't emit warnings
2306		 * for that case.
2307		 */
2308		if (ct->ct_luns[lun_id] == ctl_lun_id)
2309			return (0);
2310		CFISCSI_WARN("lun %ld already allocated", lun_id);
2311		return (-1);
2312	}
2313
2314#if 0
2315	CFISCSI_DEBUG("adding mapping for lun %ld, target %s "
2316	    "to ctl lun %ld", lun_id, ct->ct_name, ctl_lun_id);
2317#endif
2318
2319	ct->ct_luns[lun_id] = ctl_lun_id;
2320
2321	return (0);
2322}
2323
2324static int
2325cfiscsi_lun_enable(void *arg, struct ctl_id target_id, int lun_id)
2326{
2327	struct cfiscsi_softc *softc;
2328	struct cfiscsi_target *ct;
2329	const char *target = NULL;
2330	const char *lun = NULL;
2331	unsigned long tmp;
2332
2333	ct = (struct cfiscsi_target *)arg;
2334	softc = ct->ct_softc;
2335
2336	target = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2337	    "cfiscsi_target");
2338	lun = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2339	    "cfiscsi_lun");
2340
2341	if (target == NULL && lun == NULL)
2342		return (0);
2343
2344	if (target == NULL || lun == NULL) {
2345		CFISCSI_WARN("lun added with cfiscsi_target, but without "
2346		    "cfiscsi_lun, or the other way around; ignoring");
2347		return (0);
2348	}
2349
2350	if (strcmp(target, ct->ct_name) != 0)
2351		return (0);
2352
2353	tmp = strtoul(lun, NULL, 10);
2354	cfiscsi_target_set_lun(ct, tmp, lun_id);
2355	return (0);
2356}
2357
2358static int
2359cfiscsi_lun_disable(void *arg, struct ctl_id target_id, int lun_id)
2360{
2361	struct cfiscsi_softc *softc;
2362	struct cfiscsi_target *ct;
2363	int i;
2364
2365	ct = (struct cfiscsi_target *)arg;
2366	softc = ct->ct_softc;
2367
2368	mtx_lock(&softc->lock);
2369	for (i = 0; i < CTL_MAX_LUNS; i++) {
2370		if (ct->ct_luns[i] != lun_id)
2371			continue;
2372		ct->ct_luns[i] = UINT32_MAX;
2373		break;
2374	}
2375	mtx_unlock(&softc->lock);
2376	return (0);
2377}
2378
2379static void
2380cfiscsi_datamove_in(union ctl_io *io)
2381{
2382	struct cfiscsi_session *cs;
2383	struct icl_pdu *request, *response;
2384	const struct iscsi_bhs_scsi_command *bhssc;
2385	struct iscsi_bhs_data_in *bhsdi;
2386	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2387	size_t len, expected_len, sg_len, buffer_offset;
2388	const char *sg_addr;
2389	int ctl_sg_count, error, i;
2390
2391	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2392	cs = PDU_SESSION(request);
2393
2394	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2395	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2396	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2397	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2398
2399	if (io->scsiio.kern_sg_entries > 0) {
2400		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2401		ctl_sg_count = io->scsiio.kern_sg_entries;
2402	} else {
2403		ctl_sglist = &ctl_sg_entry;
2404		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2405		ctl_sglist->len = io->scsiio.kern_data_len;
2406		ctl_sg_count = 1;
2407	}
2408
2409	/*
2410	 * This is the total amount of data to be transferred within the current
2411	 * SCSI command.  We need to record it so that we can properly report
2412	 * underflow/underflow.
2413	 */
2414	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2415
2416	/*
2417	 * This is the offset within the current SCSI command; for the first
2418	 * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2419	 * it will be the sum of lengths of previous ones.
2420	 */
2421	buffer_offset = io->scsiio.kern_rel_offset;
2422
2423	/*
2424	 * This is the transfer length expected by the initiator.  In theory,
2425	 * it could be different from the correct amount of data from the SCSI
2426	 * point of view, even if that doesn't make any sense.
2427	 */
2428	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2429#if 0
2430	if (expected_len != io->scsiio.kern_total_len) {
2431		CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2432		    "actual length %zd", expected_len,
2433		    (size_t)io->scsiio.kern_total_len);
2434	}
2435#endif
2436
2437	if (buffer_offset >= expected_len) {
2438#if 0
2439		CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2440		    "already sent the expected len", buffer_offset);
2441#endif
2442		io->scsiio.be_move_done(io);
2443		return;
2444	}
2445
2446	i = 0;
2447	sg_addr = NULL;
2448	sg_len = 0;
2449	response = NULL;
2450	bhsdi = NULL;
2451	for (;;) {
2452		if (response == NULL) {
2453			response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2454			if (response == NULL) {
2455				CFISCSI_SESSION_WARN(cs, "failed to "
2456				    "allocate memory; dropping connection");
2457				ctl_set_busy(&io->scsiio);
2458				io->scsiio.be_move_done(io);
2459				cfiscsi_session_terminate(cs);
2460				return;
2461			}
2462			bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2463			bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2464			bhsdi->bhsdi_initiator_task_tag =
2465			    bhssc->bhssc_initiator_task_tag;
2466			bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2467			PDU_EXPDATASN(request)++;
2468			bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2469		}
2470
2471		KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2472		if (sg_len == 0) {
2473			sg_addr = ctl_sglist[i].addr;
2474			sg_len = ctl_sglist[i].len;
2475			KASSERT(sg_len > 0, ("sg_len <= 0"));
2476		}
2477
2478		len = sg_len;
2479
2480		/*
2481		 * Truncate to maximum data segment length.
2482		 */
2483		KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2484		    ("ip_data_len %zd >= max_data_segment_length %zd",
2485		    response->ip_data_len, cs->cs_max_data_segment_length));
2486		if (response->ip_data_len + len >
2487		    cs->cs_max_data_segment_length) {
2488			len = cs->cs_max_data_segment_length -
2489			    response->ip_data_len;
2490			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2491			    len, sg_len));
2492		}
2493
2494		/*
2495		 * Truncate to expected data transfer length.
2496		 */
2497		KASSERT(buffer_offset + response->ip_data_len < expected_len,
2498		    ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2499		    buffer_offset, response->ip_data_len, expected_len));
2500		if (buffer_offset + response->ip_data_len + len > expected_len) {
2501			CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2502			    "to expected data transfer length %zd",
2503			    buffer_offset + response->ip_data_len + len, expected_len);
2504			len = expected_len - (buffer_offset + response->ip_data_len);
2505			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2506			    len, sg_len));
2507		}
2508
2509		error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2510		if (error != 0) {
2511			CFISCSI_SESSION_WARN(cs, "failed to "
2512			    "allocate memory; dropping connection");
2513			icl_pdu_free(response);
2514			ctl_set_busy(&io->scsiio);
2515			io->scsiio.be_move_done(io);
2516			cfiscsi_session_terminate(cs);
2517			return;
2518		}
2519		sg_addr += len;
2520		sg_len -= len;
2521
2522		KASSERT(buffer_offset + response->ip_data_len <= expected_len,
2523		    ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2524		    buffer_offset, response->ip_data_len, expected_len));
2525		if (buffer_offset + response->ip_data_len == expected_len) {
2526			/*
2527			 * Already have the amount of data the initiator wanted.
2528			 */
2529			break;
2530		}
2531
2532		if (sg_len == 0) {
2533			/*
2534			 * End of scatter-gather segment;
2535			 * proceed to the next one...
2536			 */
2537			if (i == ctl_sg_count - 1) {
2538				/*
2539				 * ... unless this was the last one.
2540				 */
2541				break;
2542			}
2543			i++;
2544		}
2545
2546		if (response->ip_data_len == cs->cs_max_data_segment_length) {
2547			/*
2548			 * Can't stuff more data into the current PDU;
2549			 * queue it.  Note that's not enough to check
2550			 * for kern_data_resid == 0 instead; there
2551			 * may be several Data-In PDUs for the final
2552			 * call to cfiscsi_datamove(), and we want
2553			 * to set the F flag only on the last of them.
2554			 */
2555			buffer_offset += response->ip_data_len;
2556			if (buffer_offset == io->scsiio.kern_total_len ||
2557			    buffer_offset == expected_len)
2558				bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2559			cfiscsi_pdu_queue(response);
2560			response = NULL;
2561			bhsdi = NULL;
2562		}
2563	}
2564	if (response != NULL) {
2565		buffer_offset += response->ip_data_len;
2566		if (buffer_offset == io->scsiio.kern_total_len ||
2567		    buffer_offset == expected_len)
2568			bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2569		KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2570		cfiscsi_pdu_queue(response);
2571	}
2572
2573	io->scsiio.be_move_done(io);
2574}
2575
2576static void
2577cfiscsi_datamove_out(union ctl_io *io)
2578{
2579	struct cfiscsi_session *cs;
2580	struct icl_pdu *request, *response;
2581	const struct iscsi_bhs_scsi_command *bhssc;
2582	struct iscsi_bhs_r2t *bhsr2t;
2583	struct cfiscsi_data_wait *cdw;
2584	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2585	uint32_t expected_len, r2t_off, r2t_len;
2586	uint32_t target_transfer_tag;
2587	bool done;
2588
2589	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2590	cs = PDU_SESSION(request);
2591
2592	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2593	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2594	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2595	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2596
2597	/*
2598	 * We need to record it so that we can properly report
2599	 * underflow/underflow.
2600	 */
2601	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2602
2603	/*
2604	 * Report write underflow as error since CTL and backends don't
2605	 * really support it, and SCSI does not tell how to do it right.
2606	 */
2607	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2608	if (io->scsiio.kern_rel_offset + io->scsiio.kern_data_len >
2609	    expected_len) {
2610		io->scsiio.io_hdr.port_status = 43;
2611		io->scsiio.be_move_done(io);
2612		return;
2613	}
2614
2615	target_transfer_tag =
2616	    atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2617
2618#if 0
2619	CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2620	    "task tag 0x%x, target transfer tag 0x%x",
2621	    bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2622#endif
2623	cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
2624	if (cdw == NULL) {
2625		CFISCSI_SESSION_WARN(cs, "failed to "
2626		    "allocate memory; dropping connection");
2627		ctl_set_busy(&io->scsiio);
2628		io->scsiio.be_move_done(io);
2629		cfiscsi_session_terminate(cs);
2630		return;
2631	}
2632	cdw->cdw_ctl_io = io;
2633	cdw->cdw_target_transfer_tag = target_transfer_tag;
2634	cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2635	cdw->cdw_r2t_end = io->scsiio.kern_data_len;
2636
2637	/* Set initial data pointer for the CDW respecting ext_data_filled. */
2638	if (io->scsiio.kern_sg_entries > 0) {
2639		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2640	} else {
2641		ctl_sglist = &ctl_sg_entry;
2642		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2643		ctl_sglist->len = io->scsiio.kern_data_len;
2644	}
2645	cdw->cdw_sg_index = 0;
2646	cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2647	cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2648	r2t_off = io->scsiio.ext_data_filled;
2649	while (r2t_off > 0) {
2650		if (r2t_off >= cdw->cdw_sg_len) {
2651			r2t_off -= cdw->cdw_sg_len;
2652			cdw->cdw_sg_index++;
2653			cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2654			cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2655			continue;
2656		}
2657		cdw->cdw_sg_addr += r2t_off;
2658		cdw->cdw_sg_len -= r2t_off;
2659		r2t_off = 0;
2660	}
2661
2662	if (cs->cs_immediate_data &&
2663	    io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled <
2664	    icl_pdu_data_segment_length(request)) {
2665		done = cfiscsi_handle_data_segment(request, cdw);
2666		if (done) {
2667			uma_zfree(cfiscsi_data_wait_zone, cdw);
2668			io->scsiio.be_move_done(io);
2669			return;
2670		}
2671	}
2672
2673	r2t_off = io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled;
2674	r2t_len = MIN(io->scsiio.kern_data_len - io->scsiio.ext_data_filled,
2675	    cs->cs_max_burst_length);
2676	cdw->cdw_r2t_end = io->scsiio.ext_data_filled + r2t_len;
2677
2678	CFISCSI_SESSION_LOCK(cs);
2679	TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2680	CFISCSI_SESSION_UNLOCK(cs);
2681
2682	/*
2683	 * XXX: We should limit the number of outstanding R2T PDUs
2684	 * 	per task to MaxOutstandingR2T.
2685	 */
2686	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2687	if (response == NULL) {
2688		CFISCSI_SESSION_WARN(cs, "failed to "
2689		    "allocate memory; dropping connection");
2690		ctl_set_busy(&io->scsiio);
2691		io->scsiio.be_move_done(io);
2692		cfiscsi_session_terminate(cs);
2693		return;
2694	}
2695	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2696	bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2697	bhsr2t->bhsr2t_flags = 0x80;
2698	bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2699	bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2700	bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2701	/*
2702	 * XXX: Here we assume that cfiscsi_datamove() won't ever
2703	 *	be running concurrently on several CPUs for a given
2704	 *	command.
2705	 */
2706	bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2707	PDU_R2TSN(request)++;
2708	/*
2709	 * This is the offset within the current SCSI command;
2710	 * i.e. for the first call of datamove(), it will be 0,
2711	 * and for subsequent ones it will be the sum of lengths
2712	 * of previous ones.
2713	 *
2714	 * The ext_data_filled is to account for unsolicited
2715	 * (immediate) data that might have already arrived.
2716	 */
2717	bhsr2t->bhsr2t_buffer_offset = htonl(r2t_off);
2718	/*
2719	 * This is the total length (sum of S/G lengths) this call
2720	 * to cfiscsi_datamove() is supposed to handle, limited by
2721	 * MaxBurstLength.
2722	 */
2723	bhsr2t->bhsr2t_desired_data_transfer_length = htonl(r2t_len);
2724	cfiscsi_pdu_queue(response);
2725}
2726
2727static void
2728cfiscsi_datamove(union ctl_io *io)
2729{
2730
2731	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2732		cfiscsi_datamove_in(io);
2733	else {
2734		/* We hadn't received anything during this datamove yet. */
2735		io->scsiio.ext_data_filled = 0;
2736		cfiscsi_datamove_out(io);
2737	}
2738}
2739
2740static void
2741cfiscsi_scsi_command_done(union ctl_io *io)
2742{
2743	struct icl_pdu *request, *response;
2744	struct iscsi_bhs_scsi_command *bhssc;
2745	struct iscsi_bhs_scsi_response *bhssr;
2746#ifdef DIAGNOSTIC
2747	struct cfiscsi_data_wait *cdw;
2748#endif
2749	struct cfiscsi_session *cs;
2750	uint16_t sense_length;
2751
2752	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2753	cs = PDU_SESSION(request);
2754	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2755	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2756	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2757	    ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2758
2759	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2760	//    bhssc->bhssc_initiator_task_tag);
2761
2762#ifdef DIAGNOSTIC
2763	CFISCSI_SESSION_LOCK(cs);
2764	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2765		KASSERT(bhssc->bhssc_initiator_task_tag !=
2766		    cdw->cdw_initiator_task_tag, ("dangling cdw"));
2767	CFISCSI_SESSION_UNLOCK(cs);
2768#endif
2769
2770	/*
2771	 * Do not return status for aborted commands.
2772	 * There are exceptions, but none supported by CTL yet.
2773	 */
2774	if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
2775	    (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
2776		ctl_free_io(io);
2777		icl_pdu_free(request);
2778		return;
2779	}
2780
2781	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2782	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2783	bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2784	bhssr->bhssr_flags = 0x80;
2785	/*
2786	 * XXX: We don't deal with bidirectional under/overflows;
2787	 *	does anything actually support those?
2788	 */
2789	if (PDU_TOTAL_TRANSFER_LEN(request) <
2790	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2791		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2792		bhssr->bhssr_residual_count =
2793		    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2794		    PDU_TOTAL_TRANSFER_LEN(request));
2795		//CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2796		//    ntohl(bhssr->bhssr_residual_count));
2797	} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2798	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2799		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2800		bhssr->bhssr_residual_count =
2801		    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2802		    ntohl(bhssc->bhssc_expected_data_transfer_length));
2803		//CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2804		//    ntohl(bhssr->bhssr_residual_count));
2805	}
2806	bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2807	bhssr->bhssr_status = io->scsiio.scsi_status;
2808	bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2809	bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2810
2811	if (io->scsiio.sense_len > 0) {
2812#if 0
2813		CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2814		    io->scsiio.sense_len);
2815#endif
2816		sense_length = htons(io->scsiio.sense_len);
2817		icl_pdu_append_data(response,
2818		    &sense_length, sizeof(sense_length), M_WAITOK);
2819		icl_pdu_append_data(response,
2820		    &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2821	}
2822
2823	ctl_free_io(io);
2824	icl_pdu_free(request);
2825	cfiscsi_pdu_queue(response);
2826}
2827
2828static void
2829cfiscsi_task_management_done(union ctl_io *io)
2830{
2831	struct icl_pdu *request, *response;
2832	struct iscsi_bhs_task_management_request *bhstmr;
2833	struct iscsi_bhs_task_management_response *bhstmr2;
2834	struct cfiscsi_data_wait *cdw, *tmpcdw;
2835	struct cfiscsi_session *cs;
2836
2837	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2838	cs = PDU_SESSION(request);
2839	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2840	KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2841	    ISCSI_BHS_OPCODE_TASK_REQUEST,
2842	    ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2843
2844#if 0
2845	CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2846	    bhstmr->bhstmr_initiator_task_tag,
2847	    bhstmr->bhstmr_referenced_task_tag);
2848#endif
2849
2850	if ((bhstmr->bhstmr_function & ~0x80) ==
2851	    BHSTMR_FUNCTION_ABORT_TASK) {
2852		/*
2853		 * Make sure we no longer wait for Data-Out for this command.
2854		 */
2855		CFISCSI_SESSION_LOCK(cs);
2856		TAILQ_FOREACH_SAFE(cdw,
2857		    &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2858			if (bhstmr->bhstmr_referenced_task_tag !=
2859			    cdw->cdw_initiator_task_tag)
2860				continue;
2861
2862#if 0
2863			CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2864			    "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2865#endif
2866			TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2867			    cdw, cdw_next);
2868			cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2869			uma_zfree(cfiscsi_data_wait_zone, cdw);
2870		}
2871		CFISCSI_SESSION_UNLOCK(cs);
2872	}
2873
2874	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2875	bhstmr2 = (struct iscsi_bhs_task_management_response *)
2876	    response->ip_bhs;
2877	bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2878	bhstmr2->bhstmr_flags = 0x80;
2879	if (io->io_hdr.status == CTL_SUCCESS) {
2880		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2881	} else {
2882		/*
2883		 * XXX: How to figure out what exactly went wrong?  iSCSI spec
2884		 * 	expects us to provide detailed error, e.g. "Task does
2885		 * 	not exist" or "LUN does not exist".
2886		 */
2887		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2888		bhstmr2->bhstmr_response =
2889		    BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2890	}
2891	bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2892
2893	ctl_free_io(io);
2894	icl_pdu_free(request);
2895	cfiscsi_pdu_queue(response);
2896}
2897
2898static void
2899cfiscsi_done(union ctl_io *io)
2900{
2901	struct icl_pdu *request;
2902	struct cfiscsi_session *cs;
2903
2904	KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2905		("invalid CTL status %#x", io->io_hdr.status));
2906
2907	if (io->io_hdr.io_type == CTL_IO_TASK &&
2908	    io->taskio.task_action == CTL_TASK_I_T_NEXUS_RESET) {
2909		/*
2910		 * Implicit task termination has just completed; nothing to do.
2911		 */
2912		cs = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2913		cs->cs_tasks_aborted = true;
2914		refcount_release(&cs->cs_outstanding_ctl_pdus);
2915		wakeup(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus));
2916		ctl_free_io(io);
2917		return;
2918	}
2919
2920	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2921	cs = PDU_SESSION(request);
2922	refcount_release(&cs->cs_outstanding_ctl_pdus);
2923
2924	switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2925	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2926		cfiscsi_scsi_command_done(io);
2927		break;
2928	case ISCSI_BHS_OPCODE_TASK_REQUEST:
2929		cfiscsi_task_management_done(io);
2930		break;
2931	default:
2932		panic("cfiscsi_done called with wrong opcode 0x%x",
2933		    request->ip_bhs->bhs_opcode);
2934	}
2935}
2936