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