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