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