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