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