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