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