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