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