ctl_frontend_iscsi.c revision 267639
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 267639 2014-06-19 09:46:43Z mav $
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 267639 2014-06-19 09:46:43Z mav $");
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, last;
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		/*
1106		 * Set nonzero port status; this prevents backends from
1107		 * assuming that the data transfer actually succeeded
1108		 * and writing uninitialized data to disk.
1109		 */
1110		cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 42;
1111		cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
1112		TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
1113		uma_zfree(cfiscsi_data_wait_zone, cdw);
1114	}
1115	CFISCSI_SESSION_UNLOCK(cs);
1116#endif
1117
1118	/*
1119	 * Wait for CTL to terminate all the tasks.
1120	 */
1121	for (;;) {
1122		refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1123		last = refcount_release(&cs->cs_outstanding_ctl_pdus);
1124		if (last != 0)
1125			break;
1126		CFISCSI_SESSION_WARN(cs, "waiting for CTL to terminate tasks, "
1127		    "%d remaining", cs->cs_outstanding_ctl_pdus);
1128		pause("cfiscsi_terminate", 1);
1129	}
1130}
1131
1132static void
1133cfiscsi_maintenance_thread(void *arg)
1134{
1135	struct cfiscsi_session *cs;
1136
1137	cs = arg;
1138
1139	for (;;) {
1140		CFISCSI_SESSION_LOCK(cs);
1141		if (cs->cs_terminating == false)
1142			cv_wait(&cs->cs_maintenance_cv, &cs->cs_lock);
1143		CFISCSI_SESSION_UNLOCK(cs);
1144
1145		if (cs->cs_terminating) {
1146
1147			/*
1148			 * We used to wait up to 30 seconds to deliver queued
1149			 * PDUs to the initiator.  We also tried hard to deliver
1150			 * SCSI Responses for the aborted PDUs.  We don't do
1151			 * that anymore.  We might need to revisit that.
1152			 */
1153			callout_drain(&cs->cs_callout);
1154			icl_conn_shutdown(cs->cs_conn);
1155			icl_conn_close(cs->cs_conn);
1156
1157			/*
1158			 * At this point ICL receive thread is no longer
1159			 * running; no new tasks can be queued.
1160			 */
1161			cfiscsi_session_terminate_tasks(cs);
1162			cfiscsi_session_delete(cs);
1163			kthread_exit();
1164			return;
1165		}
1166		CFISCSI_SESSION_DEBUG(cs, "nothing to do");
1167	}
1168}
1169
1170static void
1171cfiscsi_session_terminate(struct cfiscsi_session *cs)
1172{
1173
1174	if (cs->cs_terminating)
1175		return;
1176	cs->cs_terminating = true;
1177	cv_signal(&cs->cs_maintenance_cv);
1178#ifdef ICL_KERNEL_PROXY
1179	cv_signal(&cs->cs_login_cv);
1180#endif
1181}
1182
1183static int
1184cfiscsi_session_register_initiator(struct cfiscsi_session *cs)
1185{
1186	int error, i;
1187	struct cfiscsi_softc *softc;
1188
1189	KASSERT(cs->cs_ctl_initid == -1, ("already registered"));
1190
1191	softc = &cfiscsi_softc;
1192
1193	mtx_lock(&softc->lock);
1194	for (i = 0; i < softc->max_initiators; i++) {
1195		if (softc->ctl_initids[i] == 0)
1196			break;
1197	}
1198	if (i == softc->max_initiators) {
1199		CFISCSI_SESSION_WARN(cs, "too many concurrent sessions (%d)",
1200		    softc->max_initiators);
1201		mtx_unlock(&softc->lock);
1202		return (1);
1203	}
1204	softc->ctl_initids[i] = 1;
1205	mtx_unlock(&softc->lock);
1206
1207#if 0
1208	CFISCSI_SESSION_DEBUG(cs, "adding initiator id %d, max %d",
1209	    i, softc->max_initiators);
1210#endif
1211	cs->cs_ctl_initid = i;
1212	error = ctl_add_initiator(0x0, softc->fe.targ_port, cs->cs_ctl_initid);
1213	if (error != 0) {
1214		CFISCSI_SESSION_WARN(cs, "ctl_add_initiator failed with error %d", error);
1215		mtx_lock(&softc->lock);
1216		softc->ctl_initids[cs->cs_ctl_initid] = 0;
1217		mtx_unlock(&softc->lock);
1218		cs->cs_ctl_initid = -1;
1219		return (1);
1220	}
1221
1222	return (0);
1223}
1224
1225static void
1226cfiscsi_session_unregister_initiator(struct cfiscsi_session *cs)
1227{
1228	int error;
1229	struct cfiscsi_softc *softc;
1230
1231	if (cs->cs_ctl_initid == -1)
1232		return;
1233
1234	softc = &cfiscsi_softc;
1235
1236	error = ctl_remove_initiator(softc->fe.targ_port, cs->cs_ctl_initid);
1237	if (error != 0) {
1238		CFISCSI_SESSION_WARN(cs, "ctl_remove_initiator failed with error %d",
1239		    error);
1240	}
1241	mtx_lock(&softc->lock);
1242	softc->ctl_initids[cs->cs_ctl_initid] = 0;
1243	mtx_unlock(&softc->lock);
1244	cs->cs_ctl_initid = -1;
1245}
1246
1247static struct cfiscsi_session *
1248cfiscsi_session_new(struct cfiscsi_softc *softc)
1249{
1250	struct cfiscsi_session *cs;
1251	int error;
1252
1253	cs = malloc(sizeof(*cs), M_CFISCSI, M_NOWAIT | M_ZERO);
1254	if (cs == NULL) {
1255		CFISCSI_WARN("malloc failed");
1256		return (NULL);
1257	}
1258	cs->cs_ctl_initid = -1;
1259
1260	refcount_init(&cs->cs_outstanding_ctl_pdus, 0);
1261	TAILQ_INIT(&cs->cs_waiting_for_data_out);
1262	mtx_init(&cs->cs_lock, "cfiscsi_lock", NULL, MTX_DEF);
1263	cv_init(&cs->cs_maintenance_cv, "cfiscsi_mt");
1264#ifdef ICL_KERNEL_PROXY
1265	cv_init(&cs->cs_login_cv, "cfiscsi_login");
1266#endif
1267
1268	cs->cs_conn = icl_conn_new("cfiscsi", &cs->cs_lock);
1269	cs->cs_conn->ic_receive = cfiscsi_receive_callback;
1270	cs->cs_conn->ic_error = cfiscsi_error_callback;
1271	cs->cs_conn->ic_prv0 = cs;
1272
1273	error = kthread_add(cfiscsi_maintenance_thread, cs, NULL, NULL, 0, 0, "cfiscsimt");
1274	if (error != 0) {
1275		CFISCSI_SESSION_WARN(cs, "kthread_add(9) failed with error %d", error);
1276		free(cs, M_CFISCSI);
1277		return (NULL);
1278	}
1279
1280	mtx_lock(&softc->lock);
1281	cs->cs_id = softc->last_session_id + 1;
1282	softc->last_session_id++;
1283	mtx_unlock(&softc->lock);
1284
1285	mtx_lock(&softc->lock);
1286	TAILQ_INSERT_TAIL(&softc->sessions, cs, cs_next);
1287	mtx_unlock(&softc->lock);
1288
1289	/*
1290	 * Start pinging the initiator.
1291	 */
1292	callout_init(&cs->cs_callout, 1);
1293	callout_reset(&cs->cs_callout, 1 * hz, cfiscsi_callout, cs);
1294
1295	return (cs);
1296}
1297
1298static void
1299cfiscsi_session_delete(struct cfiscsi_session *cs)
1300{
1301	struct cfiscsi_softc *softc;
1302
1303	softc = &cfiscsi_softc;
1304
1305	KASSERT(cs->cs_outstanding_ctl_pdus == 0,
1306	    ("destroying session with outstanding CTL pdus"));
1307	KASSERT(TAILQ_EMPTY(&cs->cs_waiting_for_data_out),
1308	    ("destroying session with non-empty queue"));
1309
1310	cfiscsi_session_unregister_initiator(cs);
1311	if (cs->cs_target != NULL)
1312		cfiscsi_target_release(cs->cs_target);
1313	icl_conn_close(cs->cs_conn);
1314	icl_conn_free(cs->cs_conn);
1315
1316	mtx_lock(&softc->lock);
1317	TAILQ_REMOVE(&softc->sessions, cs, cs_next);
1318	mtx_unlock(&softc->lock);
1319
1320	free(cs, M_CFISCSI);
1321}
1322
1323int
1324cfiscsi_init(void)
1325{
1326	struct cfiscsi_softc *softc;
1327	struct ctl_frontend *fe;
1328	int retval;
1329
1330	softc = &cfiscsi_softc;
1331	retval = 0;
1332	bzero(softc, sizeof(*softc));
1333	mtx_init(&softc->lock, "cfiscsi", NULL, MTX_DEF);
1334
1335#ifdef ICL_KERNEL_PROXY
1336	cv_init(&softc->accept_cv, "cfiscsi_accept");
1337#endif
1338	TAILQ_INIT(&softc->sessions);
1339	TAILQ_INIT(&softc->targets);
1340
1341	fe = &softc->fe;
1342	fe->port_type = CTL_PORT_ISCSI;
1343	/* XXX KDM what should the real number be here? */
1344	fe->num_requested_ctl_io = 4096;
1345	snprintf(softc->port_name, sizeof(softc->port_name), "iscsi");
1346	fe->port_name = softc->port_name;
1347	fe->port_online = cfiscsi_online;
1348	fe->port_offline = cfiscsi_offline;
1349	fe->onoff_arg = softc;
1350	fe->targ_enable = cfiscsi_targ_enable;
1351	fe->targ_disable = cfiscsi_targ_disable;
1352	fe->lun_enable = cfiscsi_lun_enable;
1353	fe->lun_disable = cfiscsi_lun_disable;
1354	fe->targ_lun_arg = softc;
1355	fe->ioctl = cfiscsi_ioctl;
1356	fe->devid = cfiscsi_devid;
1357	fe->fe_datamove = cfiscsi_datamove;
1358	fe->fe_done = cfiscsi_done;
1359
1360	/* XXX KDM what should we report here? */
1361	/* XXX These should probably be fetched from CTL. */
1362	fe->max_targets = 1;
1363	fe->max_target_id = 15;
1364
1365	retval = ctl_frontend_register(fe, /*master_SC*/ 1);
1366	if (retval != 0) {
1367		CFISCSI_WARN("ctl_frontend_register() failed with error %d",
1368		    retval);
1369		retval = 1;
1370		goto bailout;
1371	}
1372
1373	softc->max_initiators = fe->max_initiators;
1374
1375	cfiscsi_data_wait_zone = uma_zcreate("cfiscsi_data_wait",
1376	    sizeof(struct cfiscsi_data_wait), NULL, NULL, NULL, NULL,
1377	    UMA_ALIGN_PTR, 0);
1378
1379	return (0);
1380
1381bailout:
1382	return (retval);
1383}
1384
1385static int
1386cfiscsi_module_event_handler(module_t mod, int what, void *arg)
1387{
1388
1389	switch (what) {
1390	case MOD_LOAD:
1391		return (cfiscsi_init());
1392	case MOD_UNLOAD:
1393		return (EBUSY);
1394	default:
1395		return (EOPNOTSUPP);
1396	}
1397}
1398
1399#ifdef ICL_KERNEL_PROXY
1400static void
1401cfiscsi_accept(struct socket *so, struct sockaddr *sa, int portal_id)
1402{
1403	struct cfiscsi_session *cs;
1404
1405	cs = cfiscsi_session_new(&cfiscsi_softc);
1406	if (cs == NULL) {
1407		CFISCSI_WARN("failed to create session");
1408		return;
1409	}
1410
1411	icl_conn_handoff_sock(cs->cs_conn, so);
1412	cs->cs_initiator_sa = sa;
1413	cs->cs_portal_id = portal_id;
1414	cs->cs_waiting_for_ctld = true;
1415	cv_signal(&cfiscsi_softc.accept_cv);
1416}
1417#endif
1418
1419static void
1420cfiscsi_online(void *arg)
1421{
1422	struct cfiscsi_softc *softc;
1423
1424	softc = (struct cfiscsi_softc *)arg;
1425
1426	softc->online = 1;
1427#ifdef ICL_KERNEL_PROXY
1428	if (softc->listener != NULL)
1429		icl_listen_free(softc->listener);
1430	softc->listener = icl_listen_new(cfiscsi_accept);
1431#endif
1432}
1433
1434static void
1435cfiscsi_offline(void *arg)
1436{
1437	struct cfiscsi_softc *softc;
1438	struct cfiscsi_session *cs;
1439
1440	softc = (struct cfiscsi_softc *)arg;
1441
1442	softc->online = 0;
1443
1444	mtx_lock(&softc->lock);
1445	TAILQ_FOREACH(cs, &softc->sessions, cs_next)
1446		cfiscsi_session_terminate(cs);
1447	mtx_unlock(&softc->lock);
1448
1449#ifdef ICL_KERNEL_PROXY
1450	icl_listen_free(softc->listener);
1451	softc->listener = NULL;
1452#endif
1453}
1454
1455static int
1456cfiscsi_targ_enable(void *arg, struct ctl_id targ_id)
1457{
1458
1459	return (0);
1460}
1461
1462static int
1463cfiscsi_targ_disable(void *arg, struct ctl_id targ_id)
1464{
1465
1466	return (0);
1467}
1468
1469static void
1470cfiscsi_ioctl_handoff(struct ctl_iscsi *ci)
1471{
1472	struct cfiscsi_softc *softc;
1473	struct cfiscsi_session *cs;
1474	struct cfiscsi_target *ct;
1475	struct ctl_iscsi_handoff_params *cihp;
1476	int error;
1477
1478	cihp = (struct ctl_iscsi_handoff_params *)&(ci->data);
1479	softc = &cfiscsi_softc;
1480
1481	CFISCSI_DEBUG("new connection from %s (%s) to %s",
1482	    cihp->initiator_name, cihp->initiator_addr,
1483	    cihp->target_name);
1484
1485	if (softc->online == 0) {
1486		ci->status = CTL_ISCSI_ERROR;
1487		snprintf(ci->error_str, sizeof(ci->error_str),
1488		    "%s: port offline", __func__);
1489		return;
1490	}
1491
1492	ct = cfiscsi_target_find(softc, cihp->target_name);
1493	if (ct == NULL) {
1494		ci->status = CTL_ISCSI_ERROR;
1495		snprintf(ci->error_str, sizeof(ci->error_str),
1496		    "%s: target not found", __func__);
1497		return;
1498	}
1499
1500#ifdef ICL_KERNEL_PROXY
1501	if (cihp->socket > 0 && cihp->connection_id > 0) {
1502		snprintf(ci->error_str, sizeof(ci->error_str),
1503		    "both socket and connection_id set");
1504		ci->status = CTL_ISCSI_ERROR;
1505		cfiscsi_target_release(ct);
1506		return;
1507	}
1508	if (cihp->socket == 0) {
1509		mtx_lock(&cfiscsi_softc.lock);
1510		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1511			if (cs->cs_id == cihp->socket)
1512				break;
1513		}
1514		if (cs == NULL) {
1515			mtx_unlock(&cfiscsi_softc.lock);
1516			snprintf(ci->error_str, sizeof(ci->error_str),
1517			    "connection not found");
1518			ci->status = CTL_ISCSI_ERROR;
1519			cfiscsi_target_release(ct);
1520			return;
1521		}
1522		mtx_unlock(&cfiscsi_softc.lock);
1523	} else {
1524#endif
1525		cs = cfiscsi_session_new(softc);
1526		if (cs == NULL) {
1527			ci->status = CTL_ISCSI_ERROR;
1528			snprintf(ci->error_str, sizeof(ci->error_str),
1529			    "%s: cfiscsi_session_new failed", __func__);
1530			cfiscsi_target_release(ct);
1531			return;
1532		}
1533#ifdef ICL_KERNEL_PROXY
1534	}
1535#endif
1536	cs->cs_target = ct;
1537
1538	/*
1539	 * First PDU of Full Feature phase has the same CmdSN as the last
1540	 * PDU from the Login Phase received from the initiator.  Thus,
1541	 * the -1 below.
1542	 */
1543	cs->cs_portal_group_tag = cihp->portal_group_tag;
1544	cs->cs_cmdsn = cihp->cmdsn;
1545	cs->cs_statsn = cihp->statsn;
1546	cs->cs_max_data_segment_length = cihp->max_recv_data_segment_length;
1547	cs->cs_max_burst_length = cihp->max_burst_length;
1548	cs->cs_immediate_data = !!cihp->immediate_data;
1549	if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1550		cs->cs_conn->ic_header_crc32c = true;
1551	if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1552		cs->cs_conn->ic_data_crc32c = true;
1553
1554	strlcpy(cs->cs_initiator_name,
1555	    cihp->initiator_name, sizeof(cs->cs_initiator_name));
1556	strlcpy(cs->cs_initiator_addr,
1557	    cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1558	strlcpy(cs->cs_initiator_alias,
1559	    cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1560
1561#ifdef ICL_KERNEL_PROXY
1562	if (cihp->socket > 0) {
1563#endif
1564		error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1565		if (error != 0) {
1566			cfiscsi_session_delete(cs);
1567			ci->status = CTL_ISCSI_ERROR;
1568			snprintf(ci->error_str, sizeof(ci->error_str),
1569			    "%s: icl_conn_handoff failed with error %d",
1570			    __func__, error);
1571			return;
1572		}
1573#ifdef ICL_KERNEL_PROXY
1574	}
1575#endif
1576
1577	/*
1578	 * Register initiator with CTL.
1579	 */
1580	cfiscsi_session_register_initiator(cs);
1581
1582#ifdef ICL_KERNEL_PROXY
1583	cs->cs_login_phase = false;
1584
1585	/*
1586	 * First PDU of the Full Feature phase has likely already arrived.
1587	 * We have to pick it up and execute properly.
1588	 */
1589	if (cs->cs_login_pdu != NULL) {
1590		CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1591		cfiscsi_pdu_handle(cs->cs_login_pdu);
1592		cs->cs_login_pdu = NULL;
1593	}
1594#endif
1595
1596	ci->status = CTL_ISCSI_OK;
1597}
1598
1599static void
1600cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1601{
1602	struct ctl_iscsi_list_params *cilp;
1603	struct cfiscsi_session *cs;
1604	struct cfiscsi_softc *softc;
1605	struct sbuf *sb;
1606	int error;
1607
1608	cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1609	softc = &cfiscsi_softc;
1610
1611	sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1612	if (sb == NULL) {
1613		ci->status = CTL_ISCSI_ERROR;
1614		snprintf(ci->error_str, sizeof(ci->error_str),
1615		    "Unable to allocate %d bytes for iSCSI session list",
1616		    cilp->alloc_len);
1617		return;
1618	}
1619
1620	sbuf_printf(sb, "<ctlislist>\n");
1621	mtx_lock(&softc->lock);
1622	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1623#ifdef ICL_KERNEL_PROXY
1624		if (cs->cs_target == NULL)
1625			continue;
1626#endif
1627		error = sbuf_printf(sb, "<connection id=\"%d\">"
1628		    "<initiator>%s</initiator>"
1629		    "<initiator_addr>%s</initiator_addr>"
1630		    "<initiator_alias>%s</initiator_alias>"
1631		    "<target>%s</target>"
1632		    "<target_alias>%s</target_alias>"
1633		    "<header_digest>%s</header_digest>"
1634		    "<data_digest>%s</data_digest>"
1635		    "<max_data_segment_length>%zd</max_data_segment_length>"
1636		    "<immediate_data>%d</immediate_data>"
1637		    "<iser>%d</iser>"
1638		    "</connection>\n",
1639		    cs->cs_id,
1640		    cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1641		    cs->cs_target->ct_name, cs->cs_target->ct_alias,
1642		    cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1643		    cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1644		    cs->cs_max_data_segment_length,
1645		    cs->cs_immediate_data,
1646		    cs->cs_conn->ic_iser);
1647		if (error != 0)
1648			break;
1649	}
1650	mtx_unlock(&softc->lock);
1651	error = sbuf_printf(sb, "</ctlislist>\n");
1652	if (error != 0) {
1653		sbuf_delete(sb);
1654		ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1655		snprintf(ci->error_str, sizeof(ci->error_str),
1656		    "Out of space, %d bytes is too small", cilp->alloc_len);
1657		return;
1658	}
1659	sbuf_finish(sb);
1660
1661	error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1662	cilp->fill_len = sbuf_len(sb) + 1;
1663	ci->status = CTL_ISCSI_OK;
1664	sbuf_delete(sb);
1665}
1666
1667static void
1668cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1669{
1670	struct icl_pdu *response;
1671	struct iscsi_bhs_asynchronous_message *bhsam;
1672	struct ctl_iscsi_terminate_params *citp;
1673	struct cfiscsi_session *cs;
1674	struct cfiscsi_softc *softc;
1675	int found = 0;
1676
1677	citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1678	softc = &cfiscsi_softc;
1679
1680	mtx_lock(&softc->lock);
1681	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1682		if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1683		    strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1684		    strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1685			continue;
1686
1687		response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1688		if (response == NULL) {
1689			/*
1690			 * Oh well.  Just terminate the connection.
1691			 */
1692		} else {
1693			bhsam = (struct iscsi_bhs_asynchronous_message *)
1694			    response->ip_bhs;
1695			bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1696			bhsam->bhsam_flags = 0x80;
1697			bhsam->bhsam_0xffffffff = 0xffffffff;
1698			bhsam->bhsam_async_event =
1699			    BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1700			cfiscsi_pdu_queue(response);
1701		}
1702		cfiscsi_session_terminate(cs);
1703		found++;
1704	}
1705	mtx_unlock(&softc->lock);
1706
1707	if (found == 0) {
1708		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1709		snprintf(ci->error_str, sizeof(ci->error_str),
1710		    "No matching connections found");
1711		return;
1712	}
1713
1714	ci->status = CTL_ISCSI_OK;
1715}
1716
1717static void
1718cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1719{
1720	struct icl_pdu *response;
1721	struct iscsi_bhs_asynchronous_message *bhsam;
1722	struct ctl_iscsi_logout_params *cilp;
1723	struct cfiscsi_session *cs;
1724	struct cfiscsi_softc *softc;
1725	int found = 0;
1726
1727	cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1728	softc = &cfiscsi_softc;
1729
1730	mtx_lock(&softc->lock);
1731	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1732		if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1733		    strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1734		    strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1735			continue;
1736
1737		response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1738		if (response == NULL) {
1739			ci->status = CTL_ISCSI_ERROR;
1740			snprintf(ci->error_str, sizeof(ci->error_str),
1741			    "Unable to allocate memory");
1742			mtx_unlock(&softc->lock);
1743			return;
1744		}
1745		bhsam =
1746		    (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1747		bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1748		bhsam->bhsam_flags = 0x80;
1749		bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1750		bhsam->bhsam_parameter3 = htons(10);
1751		cfiscsi_pdu_queue(response);
1752		found++;
1753	}
1754	mtx_unlock(&softc->lock);
1755
1756	if (found == 0) {
1757		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1758		snprintf(ci->error_str, sizeof(ci->error_str),
1759		    "No matching connections found");
1760		return;
1761	}
1762
1763	ci->status = CTL_ISCSI_OK;
1764}
1765
1766#ifdef ICL_KERNEL_PROXY
1767static void
1768cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1769{
1770	struct ctl_iscsi_listen_params *cilp;
1771	struct sockaddr *sa;
1772	int error;
1773
1774	cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1775
1776	if (cfiscsi_softc.listener == NULL) {
1777		CFISCSI_DEBUG("no listener");
1778		snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1779		ci->status = CTL_ISCSI_ERROR;
1780		return;
1781	}
1782
1783	error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1784	if (error != 0) {
1785		CFISCSI_DEBUG("getsockaddr, error %d", error);
1786		snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1787		ci->status = CTL_ISCSI_ERROR;
1788		return;
1789	}
1790
1791	error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1792	    cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1793	if (error != 0) {
1794		free(sa, M_SONAME);
1795		CFISCSI_DEBUG("icl_listen_add, error %d", error);
1796		snprintf(ci->error_str, sizeof(ci->error_str),
1797		    "icl_listen_add failed, error %d", error);
1798		ci->status = CTL_ISCSI_ERROR;
1799		return;
1800	}
1801
1802	ci->status = CTL_ISCSI_OK;
1803}
1804
1805static void
1806cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1807{
1808	struct ctl_iscsi_accept_params *ciap;
1809	struct cfiscsi_session *cs;
1810	int error;
1811
1812	ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1813
1814	mtx_lock(&cfiscsi_softc.lock);
1815	for (;;) {
1816		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1817			if (cs->cs_waiting_for_ctld)
1818				break;
1819		}
1820		if (cs != NULL)
1821			break;
1822		error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1823		if (error != 0) {
1824			mtx_unlock(&cfiscsi_softc.lock);
1825			snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1826			ci->status = CTL_ISCSI_ERROR;
1827			return;
1828		}
1829	}
1830	mtx_unlock(&cfiscsi_softc.lock);
1831
1832	cs->cs_waiting_for_ctld = false;
1833	cs->cs_login_phase = true;
1834
1835	ciap->connection_id = cs->cs_id;
1836	ciap->portal_id = cs->cs_portal_id;
1837	ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1838	error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1839	    cs->cs_initiator_sa->sa_len);
1840	if (error != 0) {
1841		snprintf(ci->error_str, sizeof(ci->error_str),
1842		    "copyout failed with error %d", error);
1843		ci->status = CTL_ISCSI_ERROR;
1844		return;
1845	}
1846
1847	ci->status = CTL_ISCSI_OK;
1848}
1849
1850static void
1851cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1852{
1853	struct ctl_iscsi_send_params *cisp;
1854	struct cfiscsi_session *cs;
1855	struct icl_pdu *ip;
1856	size_t datalen;
1857	void *data;
1858	int error;
1859
1860	cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1861
1862	mtx_lock(&cfiscsi_softc.lock);
1863	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1864		if (cs->cs_id == cisp->connection_id)
1865			break;
1866	}
1867	if (cs == NULL) {
1868		mtx_unlock(&cfiscsi_softc.lock);
1869		snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1870		ci->status = CTL_ISCSI_ERROR;
1871		return;
1872	}
1873	mtx_unlock(&cfiscsi_softc.lock);
1874
1875#if 0
1876	if (cs->cs_login_phase == false)
1877		return (EBUSY);
1878#endif
1879
1880	if (cs->cs_terminating) {
1881		snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1882		ci->status = CTL_ISCSI_ERROR;
1883		return;
1884	}
1885
1886	datalen = cisp->data_segment_len;
1887	/*
1888	 * XXX
1889	 */
1890	//if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1891	if (datalen > 65535) {
1892		snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1893		ci->status = CTL_ISCSI_ERROR;
1894		return;
1895	}
1896	if (datalen > 0) {
1897		data = malloc(datalen, M_CFISCSI, M_WAITOK);
1898		error = copyin(cisp->data_segment, data, datalen);
1899		if (error != 0) {
1900			free(data, M_CFISCSI);
1901			snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1902			ci->status = CTL_ISCSI_ERROR;
1903			return;
1904		}
1905	}
1906
1907	ip = icl_pdu_new_bhs(cs->cs_conn, M_WAITOK);
1908	memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1909	if (datalen > 0) {
1910		icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1911		free(data, M_CFISCSI);
1912	}
1913	CFISCSI_SESSION_LOCK(cs);
1914	icl_pdu_queue(ip);
1915	CFISCSI_SESSION_UNLOCK(cs);
1916	ci->status = CTL_ISCSI_OK;
1917}
1918
1919static void
1920cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1921{
1922	struct ctl_iscsi_receive_params *cirp;
1923	struct cfiscsi_session *cs;
1924	struct icl_pdu *ip;
1925	void *data;
1926	int error;
1927
1928	cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1929
1930	mtx_lock(&cfiscsi_softc.lock);
1931	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1932		if (cs->cs_id == cirp->connection_id)
1933			break;
1934	}
1935	if (cs == NULL) {
1936		mtx_unlock(&cfiscsi_softc.lock);
1937		snprintf(ci->error_str, sizeof(ci->error_str),
1938		    "connection not found");
1939		ci->status = CTL_ISCSI_ERROR;
1940		return;
1941	}
1942	mtx_unlock(&cfiscsi_softc.lock);
1943
1944#if 0
1945	if (is->is_login_phase == false)
1946		return (EBUSY);
1947#endif
1948
1949	CFISCSI_SESSION_LOCK(cs);
1950	while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
1951		error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
1952		if (error != 0) {
1953			CFISCSI_SESSION_UNLOCK(cs);
1954			snprintf(ci->error_str, sizeof(ci->error_str),
1955			    "interrupted by signal");
1956			ci->status = CTL_ISCSI_ERROR;
1957			return;
1958		}
1959	}
1960
1961	if (cs->cs_terminating) {
1962		CFISCSI_SESSION_UNLOCK(cs);
1963		snprintf(ci->error_str, sizeof(ci->error_str),
1964		    "connection terminating");
1965		ci->status = CTL_ISCSI_ERROR;
1966		return;
1967	}
1968	ip = cs->cs_login_pdu;
1969	cs->cs_login_pdu = NULL;
1970	CFISCSI_SESSION_UNLOCK(cs);
1971
1972	if (ip->ip_data_len > cirp->data_segment_len) {
1973		icl_pdu_free(ip);
1974		snprintf(ci->error_str, sizeof(ci->error_str),
1975		    "data segment too big");
1976		ci->status = CTL_ISCSI_ERROR;
1977		return;
1978	}
1979
1980	copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
1981	if (ip->ip_data_len > 0) {
1982		data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
1983		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1984		copyout(data, cirp->data_segment, ip->ip_data_len);
1985		free(data, M_CFISCSI);
1986	}
1987
1988	icl_pdu_free(ip);
1989	ci->status = CTL_ISCSI_OK;
1990}
1991
1992#endif /* !ICL_KERNEL_PROXY */
1993
1994static int
1995cfiscsi_ioctl(struct cdev *dev,
1996    u_long cmd, caddr_t addr, int flag, struct thread *td)
1997{
1998	struct ctl_iscsi *ci;
1999
2000	if (cmd != CTL_ISCSI)
2001		return (ENOTTY);
2002
2003	ci = (struct ctl_iscsi *)addr;
2004	switch (ci->type) {
2005	case CTL_ISCSI_HANDOFF:
2006		cfiscsi_ioctl_handoff(ci);
2007		break;
2008	case CTL_ISCSI_LIST:
2009		cfiscsi_ioctl_list(ci);
2010		break;
2011	case CTL_ISCSI_TERMINATE:
2012		cfiscsi_ioctl_terminate(ci);
2013		break;
2014	case CTL_ISCSI_LOGOUT:
2015		cfiscsi_ioctl_logout(ci);
2016		break;
2017#ifdef ICL_KERNEL_PROXY
2018	case CTL_ISCSI_LISTEN:
2019		cfiscsi_ioctl_listen(ci);
2020		break;
2021	case CTL_ISCSI_ACCEPT:
2022		cfiscsi_ioctl_accept(ci);
2023		break;
2024	case CTL_ISCSI_SEND:
2025		cfiscsi_ioctl_send(ci);
2026		break;
2027	case CTL_ISCSI_RECEIVE:
2028		cfiscsi_ioctl_receive(ci);
2029		break;
2030#else
2031	case CTL_ISCSI_LISTEN:
2032	case CTL_ISCSI_ACCEPT:
2033	case CTL_ISCSI_SEND:
2034	case CTL_ISCSI_RECEIVE:
2035		ci->status = CTL_ISCSI_ERROR;
2036		snprintf(ci->error_str, sizeof(ci->error_str),
2037		    "%s: CTL compiled without ICL_KERNEL_PROXY",
2038		    __func__);
2039		break;
2040#endif /* !ICL_KERNEL_PROXY */
2041	default:
2042		ci->status = CTL_ISCSI_ERROR;
2043		snprintf(ci->error_str, sizeof(ci->error_str),
2044		    "%s: invalid iSCSI request type %d", __func__, ci->type);
2045		break;
2046	}
2047
2048	return (0);
2049}
2050
2051static int
2052cfiscsi_devid(struct ctl_scsiio *ctsio, int alloc_len)
2053{
2054	struct cfiscsi_session *cs;
2055	struct scsi_vpd_device_id *devid_ptr;
2056	struct scsi_vpd_id_descriptor *desc, *desc1, *desc2, *desc3, *desc4;
2057	struct scsi_vpd_id_descriptor *desc5;
2058	struct scsi_vpd_id_t10 *t10id;
2059	struct ctl_lun *lun;
2060	const struct icl_pdu *request;
2061	int i, ret;
2062	char *val;
2063	size_t data_len, devid_len, wwnn_len, wwpn_len, lun_name_len;
2064
2065	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
2066	request = ctsio->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2067	cs = PDU_SESSION(request);
2068
2069	wwpn_len = strlen(cs->cs_target->ct_name);
2070	wwpn_len += strlen(",t,0x0001");
2071	wwpn_len += 1; /* '\0' */
2072	if ((wwpn_len % 4) != 0)
2073		wwpn_len += (4 - (wwpn_len % 4));
2074
2075	wwnn_len = strlen(cs->cs_target->ct_name);
2076	wwnn_len += 1; /* '\0' */
2077	if ((wwnn_len % 4) != 0)
2078		wwnn_len += (4 - (wwnn_len % 4));
2079
2080	if (lun == NULL) {
2081		devid_len = CTL_DEVID_MIN_LEN;
2082		lun_name_len = 0;
2083	} else {
2084		devid_len = max(CTL_DEVID_MIN_LEN,
2085		    strnlen(lun->be_lun->device_id, CTL_DEVID_LEN));
2086		lun_name_len = strlen(cs->cs_target->ct_name);
2087		lun_name_len += strlen(",lun,XXXXXXXX");
2088		lun_name_len += 1; /* '\0' */
2089		if ((lun_name_len % 4) != 0)
2090			lun_name_len += (4 - (lun_name_len % 4));
2091	}
2092
2093	data_len = sizeof(struct scsi_vpd_device_id) +
2094		sizeof(struct scsi_vpd_id_descriptor) +
2095		sizeof(struct scsi_vpd_id_t10) + devid_len +
2096		sizeof(struct scsi_vpd_id_descriptor) + lun_name_len +
2097		sizeof(struct scsi_vpd_id_descriptor) + wwnn_len +
2098		sizeof(struct scsi_vpd_id_descriptor) + wwpn_len +
2099		sizeof(struct scsi_vpd_id_descriptor) +
2100		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
2101		sizeof(struct scsi_vpd_id_descriptor) +
2102		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
2103
2104	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
2105	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
2106	ctsio->kern_sg_entries = 0;
2107
2108	if (data_len < alloc_len) {
2109		ctsio->residual = alloc_len - data_len;
2110		ctsio->kern_data_len = data_len;
2111		ctsio->kern_total_len = data_len;
2112	} else {
2113		ctsio->residual = 0;
2114		ctsio->kern_data_len = alloc_len;
2115		ctsio->kern_total_len = alloc_len;
2116	}
2117	ctsio->kern_data_resid = 0;
2118	ctsio->kern_rel_offset = 0;
2119	ctsio->kern_sg_entries = 0;
2120
2121	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
2122	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
2123	desc1 = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
2124	    sizeof(struct scsi_vpd_id_t10) + devid_len);
2125	desc2 = (struct scsi_vpd_id_descriptor *)(&desc1->identifier[0] +
2126	    lun_name_len);
2127	desc3 = (struct scsi_vpd_id_descriptor *)(&desc2->identifier[0] +
2128	    wwnn_len);
2129	desc4 = (struct scsi_vpd_id_descriptor *)(&desc3->identifier[0] +
2130	    wwpn_len);
2131	desc5 = (struct scsi_vpd_id_descriptor *)(&desc4->identifier[0] +
2132	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
2133
2134	if (lun != NULL)
2135		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
2136		    lun->be_lun->lun_type;
2137	else
2138		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
2139
2140	devid_ptr->page_code = SVPD_DEVICE_ID;
2141
2142	scsi_ulto2b(data_len - 4, devid_ptr->length);
2143
2144	/*
2145	 * We're using a LUN association here.  i.e., this device ID is a
2146	 * per-LUN identifier.
2147	 */
2148	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_ASCII;
2149	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
2150	desc->length = sizeof(*t10id) + devid_len;
2151	if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "vendor")) == NULL) {
2152		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
2153	} else {
2154		memset(t10id->vendor, ' ', sizeof(t10id->vendor));
2155		strncpy(t10id->vendor, val,
2156		    min(sizeof(t10id->vendor), strlen(val)));
2157	}
2158
2159	/*
2160	 * If we've actually got a backend, copy the device id from the
2161	 * per-LUN data.  Otherwise, set it to all spaces.
2162	 */
2163	if (lun != NULL) {
2164		/*
2165		 * Copy the backend's LUN ID.
2166		 */
2167		strncpy((char *)t10id->vendor_spec_id,
2168		    (char *)lun->be_lun->device_id, devid_len);
2169	} else {
2170		/*
2171		 * No backend, set this to spaces.
2172		 */
2173		memset(t10id->vendor_spec_id, 0x20, devid_len);
2174	}
2175
2176	/*
2177	 * desc1 is for the unique LUN name.
2178	 *
2179	 * XXX: According to SPC-3, LUN must report the same ID through
2180	 *      all the ports.  The code below, however, reports the
2181	 *      ID only via iSCSI.
2182	 */
2183	desc1->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2184	desc1->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
2185		SVPD_ID_TYPE_SCSI_NAME;
2186	desc1->length = lun_name_len;
2187	if (lun != NULL) {
2188		/*
2189		 * Find the per-target LUN number.
2190		 */
2191		for (i = 0; i < CTL_MAX_LUNS; i++) {
2192			if (cs->cs_target->ct_luns[i] == lun->lun)
2193				break;
2194		}
2195		KASSERT(i < CTL_MAX_LUNS,
2196		    ("lun %jd not found", (uintmax_t)lun->lun));
2197		ret = snprintf(desc1->identifier, lun_name_len, "%s,lun,%d",
2198		    cs->cs_target->ct_name, i);
2199		KASSERT(ret > 0 && ret <= lun_name_len, ("bad snprintf"));
2200	} else {
2201		KASSERT(lun_name_len == 0, ("no lun, but lun_name_len != 0"));
2202	}
2203
2204	/*
2205	 * desc2 is for the Target Name.
2206	 */
2207	desc2->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2208	desc2->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2209	    SVPD_ID_TYPE_SCSI_NAME;
2210	desc2->length = wwnn_len;
2211	snprintf(desc2->identifier, wwnn_len, "%s", cs->cs_target->ct_name);
2212
2213	/*
2214	 * desc3 is for the WWPN which is a port asscociation.
2215	 */
2216	desc3->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2217	desc3->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2218	    SVPD_ID_TYPE_SCSI_NAME;
2219	desc3->length = wwpn_len;
2220	snprintf(desc3->identifier, wwpn_len, "%s,t,0x%4.4x",
2221	    cs->cs_target->ct_name, cs->cs_portal_group_tag);
2222
2223	/*
2224	 * desc3 is for the Relative Target Port(type 4h) identifier
2225	 */
2226	desc4->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_BINARY;
2227	desc4->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2228	    SVPD_ID_TYPE_RELTARG;
2229	desc4->length = 4;
2230	desc4->identifier[3] = 1;
2231
2232	/*
2233	 * desc4 is for the Target Port Group(type 5h) identifier
2234	 */
2235	desc5->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_BINARY;
2236	desc5->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2237	    SVPD_ID_TYPE_TPORTGRP;
2238	desc5->length = 4;
2239	desc5->identifier[3] = 1;
2240
2241	ctsio->scsi_status = SCSI_STATUS_OK;
2242
2243	ctsio->be_move_done = ctl_config_move_done;
2244	ctl_datamove((union ctl_io *)ctsio);
2245
2246	return (CTL_RETVAL_COMPLETE);
2247}
2248
2249static void
2250cfiscsi_target_hold(struct cfiscsi_target *ct)
2251{
2252
2253	refcount_acquire(&ct->ct_refcount);
2254}
2255
2256static void
2257cfiscsi_target_release(struct cfiscsi_target *ct)
2258{
2259	struct cfiscsi_softc *softc;
2260
2261	softc = ct->ct_softc;
2262	mtx_lock(&softc->lock);
2263	if (refcount_release(&ct->ct_refcount)) {
2264		TAILQ_REMOVE(&softc->targets, ct, ct_next);
2265		mtx_unlock(&softc->lock);
2266		free(ct, M_CFISCSI);
2267
2268		return;
2269	}
2270	mtx_unlock(&softc->lock);
2271}
2272
2273static struct cfiscsi_target *
2274cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name)
2275{
2276	struct cfiscsi_target *ct;
2277
2278	mtx_lock(&softc->lock);
2279	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2280		if (strcmp(name, ct->ct_name) != 0)
2281			continue;
2282		cfiscsi_target_hold(ct);
2283		mtx_unlock(&softc->lock);
2284		return (ct);
2285	}
2286	mtx_unlock(&softc->lock);
2287
2288	return (NULL);
2289}
2290
2291static struct cfiscsi_target *
2292cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2293    const char *alias)
2294{
2295	struct cfiscsi_target *ct, *newct;
2296	int i;
2297
2298	if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2299		return (NULL);
2300
2301	newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2302
2303	mtx_lock(&softc->lock);
2304	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2305		if (strcmp(name, ct->ct_name) != 0)
2306			continue;
2307		cfiscsi_target_hold(ct);
2308		mtx_unlock(&softc->lock);
2309		free(newct, M_CFISCSI);
2310		return (ct);
2311	}
2312
2313	for (i = 0; i < CTL_MAX_LUNS; i++)
2314		newct->ct_luns[i] = -1;
2315
2316	strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2317	if (alias != NULL)
2318		strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2319	refcount_init(&newct->ct_refcount, 1);
2320	newct->ct_softc = softc;
2321	TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2322	mtx_unlock(&softc->lock);
2323
2324	return (newct);
2325}
2326
2327/*
2328 * Takes LUN from the target space and returns LUN from the CTL space.
2329 */
2330static uint32_t
2331cfiscsi_map_lun(void *arg, uint32_t lun)
2332{
2333	struct cfiscsi_session *cs;
2334
2335	cs = arg;
2336
2337	if (lun >= CTL_MAX_LUNS) {
2338		CFISCSI_DEBUG("requested lun number %d is higher "
2339		    "than maximum %d", lun, CTL_MAX_LUNS - 1);
2340		return (0xffffffff);
2341	}
2342
2343	if (cs->cs_target->ct_luns[lun] < 0)
2344		return (0xffffffff);
2345
2346	return (cs->cs_target->ct_luns[lun]);
2347}
2348
2349static int
2350cfiscsi_target_set_lun(struct cfiscsi_target *ct,
2351    unsigned long lun_id, unsigned long ctl_lun_id)
2352{
2353
2354	if (lun_id >= CTL_MAX_LUNS) {
2355		CFISCSI_WARN("requested lun number %ld is higher "
2356		    "than maximum %d", lun_id, CTL_MAX_LUNS - 1);
2357		return (-1);
2358	}
2359
2360	if (ct->ct_luns[lun_id] >= 0) {
2361		/*
2362		 * CTL calls cfiscsi_lun_enable() twice for each LUN - once
2363		 * when the LUN is created, and a second time just before
2364		 * the port is brought online; don't emit warnings
2365		 * for that case.
2366		 */
2367		if (ct->ct_luns[lun_id] == ctl_lun_id)
2368			return (0);
2369		CFISCSI_WARN("lun %ld already allocated", lun_id);
2370		return (-1);
2371	}
2372
2373#if 0
2374	CFISCSI_DEBUG("adding mapping for lun %ld, target %s "
2375	    "to ctl lun %ld", lun_id, ct->ct_name, ctl_lun_id);
2376#endif
2377
2378	ct->ct_luns[lun_id] = ctl_lun_id;
2379	cfiscsi_target_hold(ct);
2380
2381	return (0);
2382}
2383
2384static int
2385cfiscsi_target_unset_lun(struct cfiscsi_target *ct, unsigned long lun_id)
2386{
2387
2388	if (ct->ct_luns[lun_id] < 0) {
2389		CFISCSI_WARN("lun %ld not allocated", lun_id);
2390		return (-1);
2391	}
2392
2393	ct->ct_luns[lun_id] = -1;
2394	cfiscsi_target_release(ct);
2395
2396	return (0);
2397}
2398
2399static int
2400cfiscsi_lun_enable(void *arg, struct ctl_id target_id, int lun_id)
2401{
2402	struct cfiscsi_softc *softc;
2403	struct cfiscsi_target *ct;
2404	const char *target = NULL, *target_alias = NULL;
2405	const char *lun = NULL;
2406	unsigned long tmp;
2407
2408	softc = (struct cfiscsi_softc *)arg;
2409
2410	target = ctl_get_opt(control_softc->ctl_luns[lun_id]->be_lun,
2411	    "cfiscsi_target");
2412	target_alias = ctl_get_opt(control_softc->ctl_luns[lun_id]->be_lun,
2413	    "cfiscsi_target)alias");
2414	lun = ctl_get_opt(control_softc->ctl_luns[lun_id]->be_lun,
2415	    "cfiscsi_lun");
2416
2417	if (target == NULL && lun == NULL)
2418		return (0);
2419
2420	if (target == NULL || lun == NULL) {
2421		CFISCSI_WARN("lun added with cfiscsi_target, but without "
2422		    "cfiscsi_lun, or the other way around; ignoring");
2423		return (0);
2424	}
2425
2426	ct = cfiscsi_target_find_or_create(softc, target, target_alias);
2427	if (ct == NULL) {
2428		CFISCSI_WARN("failed to create target \"%s\"", target);
2429		return (0);
2430	}
2431
2432	tmp = strtoul(lun, NULL, 10);
2433	cfiscsi_target_set_lun(ct, tmp, lun_id);
2434	cfiscsi_target_release(ct);
2435	return (0);
2436}
2437
2438static int
2439cfiscsi_lun_disable(void *arg, struct ctl_id target_id, int lun_id)
2440{
2441	struct cfiscsi_softc *softc;
2442	struct cfiscsi_target *ct;
2443	int i;
2444
2445	softc = (struct cfiscsi_softc *)arg;
2446
2447	mtx_lock(&softc->lock);
2448	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2449		for (i = 0; i < CTL_MAX_LUNS; i++) {
2450			if (ct->ct_luns[i] < 0)
2451				continue;
2452			if (ct->ct_luns[i] != lun_id)
2453				continue;
2454			mtx_unlock(&softc->lock);
2455			cfiscsi_target_unset_lun(ct, i);
2456			return (0);
2457		}
2458	}
2459	mtx_unlock(&softc->lock);
2460	return (0);
2461}
2462
2463static void
2464cfiscsi_datamove_in(union ctl_io *io)
2465{
2466	struct cfiscsi_session *cs;
2467	struct icl_pdu *request, *response;
2468	const struct iscsi_bhs_scsi_command *bhssc;
2469	struct iscsi_bhs_data_in *bhsdi;
2470	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2471	size_t len, expected_len, sg_len, buffer_offset;
2472	const char *sg_addr;
2473	int ctl_sg_count, error, i;
2474
2475	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2476	cs = PDU_SESSION(request);
2477
2478	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2479	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2480	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2481	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2482
2483	if (io->scsiio.kern_sg_entries > 0) {
2484		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2485		ctl_sg_count = io->scsiio.kern_sg_entries;
2486	} else {
2487		ctl_sglist = &ctl_sg_entry;
2488		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2489		ctl_sglist->len = io->scsiio.kern_data_len;
2490		ctl_sg_count = 1;
2491	}
2492
2493	/*
2494	 * This is the total amount of data to be transferred within the current
2495	 * SCSI command.  We need to record it so that we can properly report
2496	 * underflow/underflow.
2497	 */
2498	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2499
2500	/*
2501	 * This is the offset within the current SCSI command; for the first
2502	 * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2503	 * it will be the sum of lengths of previous ones.
2504	 */
2505	buffer_offset = io->scsiio.kern_rel_offset;
2506
2507	/*
2508	 * This is the transfer length expected by the initiator.  In theory,
2509	 * it could be different from the correct amount of data from the SCSI
2510	 * point of view, even if that doesn't make any sense.
2511	 */
2512	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2513#if 0
2514	if (expected_len != io->scsiio.kern_total_len) {
2515		CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2516		    "actual length %zd", expected_len,
2517		    (size_t)io->scsiio.kern_total_len);
2518	}
2519#endif
2520
2521	if (buffer_offset >= expected_len) {
2522#if 0
2523		CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2524		    "already sent the expected len", buffer_offset);
2525#endif
2526		io->scsiio.be_move_done(io);
2527		return;
2528	}
2529
2530	i = 0;
2531	sg_addr = NULL;
2532	sg_len = 0;
2533	response = NULL;
2534	bhsdi = NULL;
2535	for (;;) {
2536		if (response == NULL) {
2537			response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2538			if (response == NULL) {
2539				CFISCSI_SESSION_WARN(cs, "failed to "
2540				    "allocate memory; dropping connection");
2541				ctl_set_busy(&io->scsiio);
2542				io->scsiio.be_move_done(io);
2543				cfiscsi_session_terminate(cs);
2544				return;
2545			}
2546			bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2547			bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2548			bhsdi->bhsdi_initiator_task_tag =
2549			    bhssc->bhssc_initiator_task_tag;
2550			bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2551			PDU_EXPDATASN(request)++;
2552			bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2553		}
2554
2555		KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2556		if (sg_len == 0) {
2557			sg_addr = ctl_sglist[i].addr;
2558			sg_len = ctl_sglist[i].len;
2559			KASSERT(sg_len > 0, ("sg_len <= 0"));
2560		}
2561
2562		len = sg_len;
2563
2564		/*
2565		 * Truncate to maximum data segment length.
2566		 */
2567		KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2568		    ("ip_data_len %zd >= max_data_segment_length %zd",
2569		    response->ip_data_len, cs->cs_max_data_segment_length));
2570		if (response->ip_data_len + len >
2571		    cs->cs_max_data_segment_length) {
2572			len = cs->cs_max_data_segment_length -
2573			    response->ip_data_len;
2574			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2575			    len, sg_len));
2576		}
2577
2578		/*
2579		 * Truncate to expected data transfer length.
2580		 */
2581		KASSERT(buffer_offset + response->ip_data_len < expected_len,
2582		    ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2583		    buffer_offset, response->ip_data_len, expected_len));
2584		if (buffer_offset + response->ip_data_len + len > expected_len) {
2585			CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2586			    "to expected data transfer length %zd",
2587			    buffer_offset + response->ip_data_len + len, expected_len);
2588			len = expected_len - (buffer_offset + response->ip_data_len);
2589			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2590			    len, sg_len));
2591		}
2592
2593		error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2594		if (error != 0) {
2595			CFISCSI_SESSION_WARN(cs, "failed to "
2596			    "allocate memory; dropping connection");
2597			icl_pdu_free(response);
2598			ctl_set_busy(&io->scsiio);
2599			io->scsiio.be_move_done(io);
2600			cfiscsi_session_terminate(cs);
2601			return;
2602		}
2603		sg_addr += len;
2604		sg_len -= len;
2605
2606		KASSERT(buffer_offset + request->ip_data_len <= expected_len,
2607		    ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2608		    buffer_offset, request->ip_data_len, expected_len));
2609		if (buffer_offset + request->ip_data_len == expected_len) {
2610			/*
2611			 * Already have the amount of data the initiator wanted.
2612			 */
2613			break;
2614		}
2615
2616		if (sg_len == 0) {
2617			/*
2618			 * End of scatter-gather segment;
2619			 * proceed to the next one...
2620			 */
2621			if (i == ctl_sg_count - 1) {
2622				/*
2623				 * ... unless this was the last one.
2624				 */
2625				break;
2626			}
2627			i++;
2628		}
2629
2630		if (response->ip_data_len == cs->cs_max_data_segment_length) {
2631			/*
2632			 * Can't stuff more data into the current PDU;
2633			 * queue it.  Note that's not enough to check
2634			 * for kern_data_resid == 0 instead; there
2635			 * may be several Data-In PDUs for the final
2636			 * call to cfiscsi_datamove(), and we want
2637			 * to set the F flag only on the last of them.
2638			 */
2639			buffer_offset += response->ip_data_len;
2640			if (buffer_offset == io->scsiio.kern_total_len ||
2641			    buffer_offset == expected_len)
2642				bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2643			cfiscsi_pdu_queue(response);
2644			response = NULL;
2645			bhsdi = NULL;
2646		}
2647	}
2648	if (response != NULL) {
2649		buffer_offset += response->ip_data_len;
2650		if (buffer_offset == io->scsiio.kern_total_len ||
2651		    buffer_offset == expected_len)
2652			bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2653		KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2654		cfiscsi_pdu_queue(response);
2655	}
2656
2657	io->scsiio.be_move_done(io);
2658}
2659
2660static void
2661cfiscsi_datamove_out(union ctl_io *io)
2662{
2663	struct cfiscsi_session *cs;
2664	struct icl_pdu *request, *response;
2665	const struct iscsi_bhs_scsi_command *bhssc;
2666	struct iscsi_bhs_r2t *bhsr2t;
2667	struct cfiscsi_data_wait *cdw;
2668	uint32_t target_transfer_tag;
2669	bool done;
2670
2671	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2672	cs = PDU_SESSION(request);
2673
2674	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2675	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2676	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2677	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2678
2679	/*
2680	 * We need to record it so that we can properly report
2681	 * underflow/underflow.
2682	 */
2683	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2684
2685	/*
2686	 * We hadn't received anything during this datamove yet.
2687	 */
2688	io->scsiio.ext_data_filled = 0;
2689
2690	target_transfer_tag =
2691	    atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2692
2693#if 0
2694	CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2695	    "task tag 0x%x, target transfer tag 0x%x",
2696	    bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2697#endif
2698	cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
2699	if (cdw == NULL) {
2700		CFISCSI_SESSION_WARN(cs, "failed to "
2701		    "allocate memory; dropping connection");
2702		ctl_set_busy(&io->scsiio);
2703		io->scsiio.be_move_done(io);
2704		cfiscsi_session_terminate(cs);
2705		return;
2706	}
2707	cdw->cdw_ctl_io = io;
2708	cdw->cdw_target_transfer_tag = target_transfer_tag;
2709	cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2710
2711	if (cs->cs_immediate_data && io->scsiio.kern_rel_offset == 0 &&
2712	    icl_pdu_data_segment_length(request) > 0) {
2713		done = cfiscsi_handle_data_segment(request, cdw);
2714		if (done) {
2715			uma_zfree(cfiscsi_data_wait_zone, cdw);
2716			io->scsiio.be_move_done(io);
2717			return;
2718		}
2719	}
2720
2721	CFISCSI_SESSION_LOCK(cs);
2722	TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2723	CFISCSI_SESSION_UNLOCK(cs);
2724
2725	/*
2726	 * XXX: We should limit the number of outstanding R2T PDUs
2727	 * 	per task to MaxOutstandingR2T.
2728	 */
2729	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2730	if (response == NULL) {
2731		CFISCSI_SESSION_WARN(cs, "failed to "
2732		    "allocate memory; dropping connection");
2733		ctl_set_busy(&io->scsiio);
2734		io->scsiio.be_move_done(io);
2735		cfiscsi_session_terminate(cs);
2736		return;
2737	}
2738	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2739	bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2740	bhsr2t->bhsr2t_flags = 0x80;
2741	bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2742	bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2743	bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2744	/*
2745	 * XXX: Here we assume that cfiscsi_datamove() won't ever
2746	 *	be running concurrently on several CPUs for a given
2747	 *	command.
2748	 */
2749	bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2750	PDU_R2TSN(request)++;
2751	/*
2752	 * This is the offset within the current SCSI command;
2753	 * i.e. for the first call of datamove(), it will be 0,
2754	 * and for subsequent ones it will be the sum of lengths
2755	 * of previous ones.
2756	 *
2757	 * The ext_data_filled is to account for unsolicited
2758	 * (immediate) data that might have already arrived.
2759	 */
2760	bhsr2t->bhsr2t_buffer_offset =
2761	    htonl(io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled);
2762	/*
2763	 * This is the total length (sum of S/G lengths) this call
2764	 * to cfiscsi_datamove() is supposed to handle.
2765	 *
2766	 * XXX: Limit it to MaxBurstLength.
2767	 */
2768	bhsr2t->bhsr2t_desired_data_transfer_length =
2769	    htonl(io->scsiio.kern_data_len - io->scsiio.ext_data_filled);
2770	cfiscsi_pdu_queue(response);
2771}
2772
2773static void
2774cfiscsi_datamove(union ctl_io *io)
2775{
2776
2777	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2778		cfiscsi_datamove_in(io);
2779	else
2780		cfiscsi_datamove_out(io);
2781}
2782
2783static void
2784cfiscsi_scsi_command_done(union ctl_io *io)
2785{
2786	struct icl_pdu *request, *response;
2787	struct iscsi_bhs_scsi_command *bhssc;
2788	struct iscsi_bhs_scsi_response *bhssr;
2789#ifdef DIAGNOSTIC
2790	struct cfiscsi_data_wait *cdw;
2791#endif
2792	struct cfiscsi_session *cs;
2793	uint16_t sense_length;
2794
2795	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2796	cs = PDU_SESSION(request);
2797	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2798	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2799	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2800	    ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2801
2802	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2803	//    bhssc->bhssc_initiator_task_tag);
2804
2805#ifdef DIAGNOSTIC
2806	CFISCSI_SESSION_LOCK(cs);
2807	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2808		KASSERT(bhssc->bhssc_initiator_task_tag !=
2809		    cdw->cdw_initiator_task_tag, ("dangling cdw"));
2810	CFISCSI_SESSION_UNLOCK(cs);
2811#endif
2812
2813	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2814	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2815	bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2816	bhssr->bhssr_flags = 0x80;
2817	/*
2818	 * XXX: We don't deal with bidirectional under/overflows;
2819	 *	does anything actually support those?
2820	 */
2821	if (PDU_TOTAL_TRANSFER_LEN(request) <
2822	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2823		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2824		bhssr->bhssr_residual_count =
2825		    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2826		    PDU_TOTAL_TRANSFER_LEN(request));
2827		//CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2828		//    ntohl(bhssr->bhssr_residual_count));
2829	} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2830	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2831		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2832		bhssr->bhssr_residual_count =
2833		    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2834		    ntohl(bhssc->bhssc_expected_data_transfer_length));
2835		//CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2836		//    ntohl(bhssr->bhssr_residual_count));
2837	}
2838	bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2839	bhssr->bhssr_status = io->scsiio.scsi_status;
2840	bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2841	bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2842
2843	if (io->scsiio.sense_len > 0) {
2844#if 0
2845		CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2846		    io->scsiio.sense_len);
2847#endif
2848		sense_length = htons(io->scsiio.sense_len);
2849		icl_pdu_append_data(response,
2850		    &sense_length, sizeof(sense_length), M_WAITOK);
2851		icl_pdu_append_data(response,
2852		    &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2853	}
2854
2855	ctl_free_io(io);
2856	icl_pdu_free(request);
2857	cfiscsi_pdu_queue(response);
2858}
2859
2860static void
2861cfiscsi_task_management_done(union ctl_io *io)
2862{
2863	struct icl_pdu *request, *response;
2864	struct iscsi_bhs_task_management_request *bhstmr;
2865	struct iscsi_bhs_task_management_response *bhstmr2;
2866	struct cfiscsi_data_wait *cdw, *tmpcdw;
2867	struct cfiscsi_session *cs;
2868
2869	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2870	cs = PDU_SESSION(request);
2871	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2872	KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2873	    ISCSI_BHS_OPCODE_TASK_REQUEST,
2874	    ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2875
2876#if 0
2877	CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2878	    bhstmr->bhstmr_initiator_task_tag,
2879	    bhstmr->bhstmr_referenced_task_tag);
2880#endif
2881
2882	if ((bhstmr->bhstmr_function & ~0x80) ==
2883	    BHSTMR_FUNCTION_ABORT_TASK) {
2884		/*
2885		 * Make sure we no longer wait for Data-Out for this command.
2886		 */
2887		CFISCSI_SESSION_LOCK(cs);
2888		TAILQ_FOREACH_SAFE(cdw,
2889		    &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2890			if (bhstmr->bhstmr_referenced_task_tag !=
2891			    cdw->cdw_initiator_task_tag)
2892				continue;
2893
2894#if 0
2895			CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2896			    "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2897#endif
2898			TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2899			    cdw, cdw_next);
2900			cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2901			uma_zfree(cfiscsi_data_wait_zone, cdw);
2902		}
2903		CFISCSI_SESSION_UNLOCK(cs);
2904	}
2905
2906	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2907	bhstmr2 = (struct iscsi_bhs_task_management_response *)
2908	    response->ip_bhs;
2909	bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2910	bhstmr2->bhstmr_flags = 0x80;
2911	if (io->io_hdr.status == CTL_SUCCESS) {
2912		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2913	} else {
2914		/*
2915		 * XXX: How to figure out what exactly went wrong?  iSCSI spec
2916		 * 	expects us to provide detailed error, e.g. "Task does
2917		 * 	not exist" or "LUN does not exist".
2918		 */
2919		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2920		bhstmr2->bhstmr_response =
2921		    BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2922	}
2923	bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2924
2925	ctl_free_io(io);
2926	icl_pdu_free(request);
2927	cfiscsi_pdu_queue(response);
2928}
2929
2930static void
2931cfiscsi_done(union ctl_io *io)
2932{
2933	struct icl_pdu *request;
2934	struct cfiscsi_session *cs;
2935
2936	KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2937		("invalid CTL status %#x", io->io_hdr.status));
2938
2939	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2940	if (request == NULL) {
2941		/*
2942		 * Implicit task termination has just completed; nothing to do.
2943		 */
2944		return;
2945	}
2946
2947	cs = PDU_SESSION(request);
2948	refcount_release(&cs->cs_outstanding_ctl_pdus);
2949
2950	switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2951	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2952		cfiscsi_scsi_command_done(io);
2953		break;
2954	case ISCSI_BHS_OPCODE_TASK_REQUEST:
2955		cfiscsi_task_management_done(io);
2956		break;
2957	default:
2958		panic("cfiscsi_done called with wrong opcode 0x%x",
2959		    request->ip_bhs->bhs_opcode);
2960	}
2961}
2962