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