ctl_frontend_iscsi.c revision 268685
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 268685 2014-07-15 17:08:04Z 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 268685 2014-07-15 17:08:04Z mav $");
38
39#include <sys/param.h>
40#include <sys/capability.h>
41#include <sys/condvar.h>
42#include <sys/file.h>
43#include <sys/kernel.h>
44#include <sys/kthread.h>
45#include <sys/lock.h>
46#include <sys/malloc.h>
47#include <sys/module.h>
48#include <sys/mutex.h>
49#include <sys/queue.h>
50#include <sys/sbuf.h>
51#include <sys/sysctl.h>
52#include <sys/systm.h>
53#include <sys/uio.h>
54#include <sys/unistd.h>
55#include <vm/uma.h>
56
57#include <cam/scsi/scsi_all.h>
58#include <cam/scsi/scsi_da.h>
59#include <cam/ctl/ctl_io.h>
60#include <cam/ctl/ctl.h>
61#include <cam/ctl/ctl_backend.h>
62#include <cam/ctl/ctl_error.h>
63#include <cam/ctl/ctl_frontend.h>
64#include <cam/ctl/ctl_frontend_internal.h>
65#include <cam/ctl/ctl_debug.h>
66#include <cam/ctl/ctl_ha.h>
67#include <cam/ctl/ctl_ioctl.h>
68#include <cam/ctl/ctl_private.h>
69
70#include "../../dev/iscsi/icl.h"
71#include "../../dev/iscsi/iscsi_proto.h"
72#include "ctl_frontend_iscsi.h"
73
74#ifdef ICL_KERNEL_PROXY
75#include <sys/socketvar.h>
76#endif
77
78#ifdef ICL_KERNEL_PROXY
79FEATURE(cfiscsi_kernel_proxy, "iSCSI target built with ICL_KERNEL_PROXY");
80#endif
81
82static MALLOC_DEFINE(M_CFISCSI, "cfiscsi", "Memory used for CTL iSCSI frontend");
83static uma_zone_t cfiscsi_data_wait_zone;
84
85SYSCTL_NODE(_kern_cam_ctl, OID_AUTO, iscsi, CTLFLAG_RD, 0,
86    "CAM Target Layer iSCSI Frontend");
87static int debug = 3;
88TUNABLE_INT("kern.cam.ctl.iscsi.debug", &debug);
89SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, debug, CTLFLAG_RWTUN,
90    &debug, 1, "Enable debug messages");
91static int ping_timeout = 5;
92TUNABLE_INT("kern.cam.ctl.iscsi.ping_timeout", &ping_timeout);
93SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, ping_timeout, CTLFLAG_RWTUN,
94    &ping_timeout, 5, "Interval between ping (NOP-Out) requests, in seconds");
95static int login_timeout = 60;
96TUNABLE_INT("kern.cam.ctl.iscsi.login_timeout", &login_timeout);
97SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, login_timeout, CTLFLAG_RWTUN,
98    &login_timeout, 60, "Time to wait for ctld(8) to finish Login Phase, in seconds");
99static int maxcmdsn_delta = 256;
100TUNABLE_INT("kern.cam.ctl.iscsi.maxcmdsn_delta", &maxcmdsn_delta);
101SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, maxcmdsn_delta, CTLFLAG_RWTUN,
102    &maxcmdsn_delta, 256, "Number of commands the initiator can send "
103    "without confirmation");
104
105#define	CFISCSI_DEBUG(X, ...)						\
106	do {								\
107		if (debug > 1) {					\
108			printf("%s: " X "\n",				\
109			    __func__, ## __VA_ARGS__);			\
110		}							\
111	} while (0)
112
113#define	CFISCSI_WARN(X, ...)						\
114	do {								\
115		if (debug > 0) {					\
116			printf("WARNING: %s: " X "\n",			\
117			    __func__, ## __VA_ARGS__);			\
118		}							\
119	} while (0)
120
121#define	CFISCSI_SESSION_DEBUG(S, X, ...)				\
122	do {								\
123		if (debug > 1) {					\
124			printf("%s: %s (%s): " X "\n",			\
125			    __func__, S->cs_initiator_addr,		\
126			    S->cs_initiator_name, ## __VA_ARGS__);	\
127		}							\
128	} while (0)
129
130#define	CFISCSI_SESSION_WARN(S, X, ...)					\
131	do  {								\
132		if (debug > 0) {					\
133			printf("WARNING: %s (%s): " X "\n",		\
134			    S->cs_initiator_addr,			\
135			    S->cs_initiator_name, ## __VA_ARGS__);	\
136		}							\
137	} while (0)
138
139#define CFISCSI_SESSION_LOCK(X)		mtx_lock(&X->cs_lock)
140#define CFISCSI_SESSION_UNLOCK(X)	mtx_unlock(&X->cs_lock)
141#define CFISCSI_SESSION_LOCK_ASSERT(X)	mtx_assert(&X->cs_lock, MA_OWNED)
142
143#define	CONN_SESSION(X)			((struct cfiscsi_session *)(X)->ic_prv0)
144#define	PDU_SESSION(X)			CONN_SESSION((X)->ip_conn)
145#define	PDU_EXPDATASN(X)		(X)->ip_prv0
146#define	PDU_TOTAL_TRANSFER_LEN(X)	(X)->ip_prv1
147#define	PDU_R2TSN(X)			(X)->ip_prv2
148
149int		cfiscsi_init(void);
150static void	cfiscsi_online(void *arg);
151static void	cfiscsi_offline(void *arg);
152static int	cfiscsi_lun_enable(void *arg,
153		    struct ctl_id target_id, int lun_id);
154static int	cfiscsi_lun_disable(void *arg,
155		    struct ctl_id target_id, int lun_id);
156static uint32_t	cfiscsi_lun_map(void *arg, uint32_t lun);
157static int	cfiscsi_ioctl(struct cdev *dev,
158		    u_long cmd, caddr_t addr, int flag, struct thread *td);
159static void	cfiscsi_datamove(union ctl_io *io);
160static void	cfiscsi_done(union ctl_io *io);
161static bool	cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request);
162static void	cfiscsi_pdu_handle_nop_out(struct icl_pdu *request);
163static void	cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request);
164static void	cfiscsi_pdu_handle_task_request(struct icl_pdu *request);
165static void	cfiscsi_pdu_handle_data_out(struct icl_pdu *request);
166static void	cfiscsi_pdu_handle_logout_request(struct icl_pdu *request);
167static void	cfiscsi_session_terminate(struct cfiscsi_session *cs);
168static struct cfiscsi_target	*cfiscsi_target_find(struct cfiscsi_softc
169		    *softc, const char *name);
170static struct cfiscsi_target	*cfiscsi_target_find_or_create(
171    struct cfiscsi_softc *softc, const char *name, const char *alias);
172static void	cfiscsi_target_release(struct cfiscsi_target *ct);
173static void	cfiscsi_session_delete(struct cfiscsi_session *cs);
174
175static struct cfiscsi_softc cfiscsi_softc;
176extern struct ctl_softc *control_softc;
177
178static struct ctl_frontend cfiscsi_frontend =
179{
180	.name = "iscsi",
181	.init = cfiscsi_init,
182	.ioctl = cfiscsi_ioctl,
183};
184CTL_FRONTEND_DECLARE(ctlcfiscsi, cfiscsi_frontend);
185
186static struct icl_pdu *
187cfiscsi_pdu_new_response(struct icl_pdu *request, int flags)
188{
189
190	return (icl_pdu_new_bhs(request->ip_conn, flags));
191}
192
193static bool
194cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request)
195{
196	const struct iscsi_bhs_scsi_command *bhssc;
197	struct cfiscsi_session *cs;
198	uint32_t cmdsn, expstatsn;
199
200	cs = PDU_SESSION(request);
201
202	/*
203	 * Every incoming PDU - not just NOP-Out - resets the ping timer.
204	 * The purpose of the timeout is to reset the connection when it stalls;
205	 * we don't want this to happen when NOP-In or NOP-Out ends up delayed
206	 * in some queue.
207	 *
208	 * XXX: Locking?
209	 */
210	cs->cs_timeout = 0;
211
212	/*
213	 * Data-Out PDUs don't contain CmdSN.
214	 */
215	if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
216	    ISCSI_BHS_OPCODE_SCSI_DATA_OUT)
217		return (false);
218
219	/*
220	 * We're only using fields common for all the request
221	 * (initiator -> target) PDUs.
222	 */
223	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
224	cmdsn = ntohl(bhssc->bhssc_cmdsn);
225	expstatsn = ntohl(bhssc->bhssc_expstatsn);
226
227	CFISCSI_SESSION_LOCK(cs);
228#if 0
229	if (expstatsn != cs->cs_statsn) {
230		CFISCSI_SESSION_DEBUG(cs, "received PDU with ExpStatSN %d, "
231		    "while current StatSN is %d", expstatsn,
232		    cs->cs_statsn);
233	}
234#endif
235
236	/*
237	 * The target MUST silently ignore any non-immediate command outside
238	 * of this range.
239	 */
240	if (cmdsn < cs->cs_cmdsn || cmdsn > cs->cs_cmdsn + maxcmdsn_delta) {
241		CFISCSI_SESSION_UNLOCK(cs);
242		CFISCSI_SESSION_WARN(cs, "received PDU with CmdSN %d, "
243		    "while expected CmdSN was %d", cmdsn, cs->cs_cmdsn);
244		return (true);
245	}
246
247	if ((request->ip_bhs->bhs_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0)
248		cs->cs_cmdsn++;
249
250	CFISCSI_SESSION_UNLOCK(cs);
251
252	return (false);
253}
254
255static void
256cfiscsi_pdu_handle(struct icl_pdu *request)
257{
258	struct cfiscsi_session *cs;
259	bool ignore;
260
261	cs = PDU_SESSION(request);
262
263	ignore = cfiscsi_pdu_update_cmdsn(request);
264	if (ignore) {
265		icl_pdu_free(request);
266		return;
267	}
268
269	/*
270	 * Handle the PDU; this includes e.g. receiving the remaining
271	 * part of PDU and submitting the SCSI command to CTL
272	 * or queueing a reply.  The handling routine is responsible
273	 * for freeing the PDU when it's no longer needed.
274	 */
275	switch (request->ip_bhs->bhs_opcode &
276	    ~ISCSI_BHS_OPCODE_IMMEDIATE) {
277	case ISCSI_BHS_OPCODE_NOP_OUT:
278		cfiscsi_pdu_handle_nop_out(request);
279		break;
280	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
281		cfiscsi_pdu_handle_scsi_command(request);
282		break;
283	case ISCSI_BHS_OPCODE_TASK_REQUEST:
284		cfiscsi_pdu_handle_task_request(request);
285		break;
286	case ISCSI_BHS_OPCODE_SCSI_DATA_OUT:
287		cfiscsi_pdu_handle_data_out(request);
288		break;
289	case ISCSI_BHS_OPCODE_LOGOUT_REQUEST:
290		cfiscsi_pdu_handle_logout_request(request);
291		break;
292	default:
293		CFISCSI_SESSION_WARN(cs, "received PDU with unsupported "
294		    "opcode 0x%x; dropping connection",
295		    request->ip_bhs->bhs_opcode);
296		icl_pdu_free(request);
297		cfiscsi_session_terminate(cs);
298	}
299
300}
301
302static void
303cfiscsi_receive_callback(struct icl_pdu *request)
304{
305	struct cfiscsi_session *cs;
306
307	cs = PDU_SESSION(request);
308
309#ifdef ICL_KERNEL_PROXY
310	if (cs->cs_waiting_for_ctld || cs->cs_login_phase) {
311		if (cs->cs_login_pdu == NULL)
312			cs->cs_login_pdu = request;
313		else
314			icl_pdu_free(request);
315		cv_signal(&cs->cs_login_cv);
316		return;
317	}
318#endif
319
320	cfiscsi_pdu_handle(request);
321}
322
323static void
324cfiscsi_error_callback(struct icl_conn *ic)
325{
326	struct cfiscsi_session *cs;
327
328	cs = CONN_SESSION(ic);
329
330	CFISCSI_SESSION_WARN(cs, "connection error; dropping connection");
331	cfiscsi_session_terminate(cs);
332}
333
334static int
335cfiscsi_pdu_prepare(struct icl_pdu *response)
336{
337	struct cfiscsi_session *cs;
338	struct iscsi_bhs_scsi_response *bhssr;
339	bool advance_statsn = true;
340
341	cs = PDU_SESSION(response);
342
343	CFISCSI_SESSION_LOCK_ASSERT(cs);
344
345	/*
346	 * We're only using fields common for all the response
347	 * (target -> initiator) PDUs.
348	 */
349	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
350
351	/*
352	 * 10.8.3: "The StatSN for this connection is not advanced
353	 * after this PDU is sent."
354	 */
355	if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_R2T)
356		advance_statsn = false;
357
358	/*
359	 * 10.19.2: "However, when the Initiator Task Tag is set to 0xffffffff,
360	 * StatSN for the connection is not advanced after this PDU is sent."
361	 */
362	if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_NOP_IN &&
363	    bhssr->bhssr_initiator_task_tag == 0xffffffff)
364		advance_statsn = false;
365
366	/*
367	 * See the comment below - StatSN is not meaningful and must
368	 * not be advanced.
369	 */
370	if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_SCSI_DATA_IN)
371		advance_statsn = false;
372
373	/*
374	 * 10.7.3: "The fields StatSN, Status, and Residual Count
375	 * only have meaningful content if the S bit is set to 1."
376	 */
377	if (bhssr->bhssr_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_IN)
378		bhssr->bhssr_statsn = htonl(cs->cs_statsn);
379	bhssr->bhssr_expcmdsn = htonl(cs->cs_cmdsn);
380	bhssr->bhssr_maxcmdsn = htonl(cs->cs_cmdsn + maxcmdsn_delta);
381
382	if (advance_statsn)
383		cs->cs_statsn++;
384
385	return (0);
386}
387
388static void
389cfiscsi_pdu_queue(struct icl_pdu *response)
390{
391	struct cfiscsi_session *cs;
392
393	cs = PDU_SESSION(response);
394
395	CFISCSI_SESSION_LOCK(cs);
396	cfiscsi_pdu_prepare(response);
397	icl_pdu_queue(response);
398	CFISCSI_SESSION_UNLOCK(cs);
399}
400
401static uint32_t
402cfiscsi_decode_lun(uint64_t encoded)
403{
404	uint8_t lun[8];
405	uint32_t result;
406
407	/*
408	 * The LUN field in iSCSI PDUs may look like an ordinary 64 bit number,
409	 * but is in fact an evil, multidimensional structure defined
410	 * in SCSI Architecture Model 5 (SAM-5), section 4.6.
411	 */
412	memcpy(lun, &encoded, sizeof(lun));
413	switch (lun[0] & 0xC0) {
414	case 0x00:
415		if ((lun[0] & 0x3f) != 0 || lun[2] != 0 || lun[3] != 0 ||
416		    lun[4] != 0 || lun[5] != 0 || lun[6] != 0 || lun[7] != 0) {
417			CFISCSI_WARN("malformed LUN "
418			    "(peripheral device addressing method): 0x%jx",
419			    (uintmax_t)encoded);
420			result = 0xffffffff;
421			break;
422		}
423		result = lun[1];
424		break;
425	case 0x40:
426		if (lun[2] != 0 || lun[3] != 0 || lun[4] != 0 || lun[5] != 0 ||
427		    lun[6] != 0 || lun[7] != 0) {
428			CFISCSI_WARN("malformed LUN "
429			    "(flat address space addressing method): 0x%jx",
430			    (uintmax_t)encoded);
431			result = 0xffffffff;
432			break;
433		}
434		result = ((lun[0] & 0x3f) << 8) + lun[1];
435		break;
436	case 0xC0:
437		if (lun[0] != 0xD2 || lun[4] != 0 || lun[5] != 0 ||
438		    lun[6] != 0 || lun[7] != 0) {
439			CFISCSI_WARN("malformed LUN (extended flat "
440			    "address space addressing method): 0x%jx",
441			    (uintmax_t)encoded);
442			result = 0xffffffff;
443			break;
444		}
445		result = (lun[1] << 16) + (lun[2] << 8) + lun[3];
446	default:
447		CFISCSI_WARN("unsupported LUN format 0x%jx",
448		    (uintmax_t)encoded);
449		result = 0xffffffff;
450		break;
451	}
452
453	return (result);
454}
455
456static void
457cfiscsi_pdu_handle_nop_out(struct icl_pdu *request)
458{
459	struct cfiscsi_session *cs;
460	struct iscsi_bhs_nop_out *bhsno;
461	struct iscsi_bhs_nop_in *bhsni;
462	struct icl_pdu *response;
463	void *data = NULL;
464	size_t datasize;
465	int error;
466
467	cs = PDU_SESSION(request);
468	bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
469
470	if (bhsno->bhsno_initiator_task_tag == 0xffffffff) {
471		/*
472		 * Nothing to do, iscsi_pdu_update_statsn() already
473		 * zeroed the timeout.
474		 */
475		icl_pdu_free(request);
476		return;
477	}
478
479	datasize = icl_pdu_data_segment_length(request);
480	if (datasize > 0) {
481		data = malloc(datasize, M_CFISCSI, M_NOWAIT | M_ZERO);
482		if (data == NULL) {
483			CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
484			    "dropping connection");
485			icl_pdu_free(request);
486			cfiscsi_session_terminate(cs);
487			return;
488		}
489		icl_pdu_get_data(request, 0, data, datasize);
490	}
491
492	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
493	if (response == NULL) {
494		CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
495		    "droppping connection");
496		free(data, M_CFISCSI);
497		icl_pdu_free(request);
498		cfiscsi_session_terminate(cs);
499		return;
500	}
501	bhsni = (struct iscsi_bhs_nop_in *)response->ip_bhs;
502	bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
503	bhsni->bhsni_flags = 0x80;
504	bhsni->bhsni_initiator_task_tag = bhsno->bhsno_initiator_task_tag;
505	bhsni->bhsni_target_transfer_tag = 0xffffffff;
506	if (datasize > 0) {
507		error = icl_pdu_append_data(response, data, datasize, M_NOWAIT);
508		if (error != 0) {
509			CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
510			    "dropping connection");
511			free(data, M_CFISCSI);
512			icl_pdu_free(request);
513			icl_pdu_free(response);
514			cfiscsi_session_terminate(cs);
515			return;
516		}
517		free(data, M_CFISCSI);
518	}
519
520	icl_pdu_free(request);
521	cfiscsi_pdu_queue(response);
522}
523
524static void
525cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request)
526{
527	struct iscsi_bhs_scsi_command *bhssc;
528	struct cfiscsi_session *cs;
529	union ctl_io *io;
530	int error;
531
532	cs = PDU_SESSION(request);
533	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
534	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
535	//    bhssc->bhssc_initiator_task_tag);
536
537	if (request->ip_data_len > 0 && cs->cs_immediate_data == false) {
538		CFISCSI_SESSION_WARN(cs, "unsolicited data with "
539		    "ImmediateData=No; dropping connection");
540		icl_pdu_free(request);
541		cfiscsi_session_terminate(cs);
542		return;
543	}
544	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
545	if (io == NULL) {
546		CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io; "
547		    "dropping connection");
548		icl_pdu_free(request);
549		cfiscsi_session_terminate(cs);
550		return;
551	}
552	ctl_zero_io(io);
553	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
554	io->io_hdr.io_type = CTL_IO_SCSI;
555	io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
556	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
557	io->io_hdr.nexus.targ_target.id = 0;
558	io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhssc->bhssc_lun);
559	io->scsiio.tag_num = bhssc->bhssc_initiator_task_tag;
560	switch ((bhssc->bhssc_flags & BHSSC_FLAGS_ATTR)) {
561	case BHSSC_FLAGS_ATTR_UNTAGGED:
562		io->scsiio.tag_type = CTL_TAG_UNTAGGED;
563		break;
564	case BHSSC_FLAGS_ATTR_SIMPLE:
565		io->scsiio.tag_type = CTL_TAG_SIMPLE;
566		break;
567	case BHSSC_FLAGS_ATTR_ORDERED:
568        	io->scsiio.tag_type = CTL_TAG_ORDERED;
569		break;
570	case BHSSC_FLAGS_ATTR_HOQ:
571        	io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
572		break;
573	case BHSSC_FLAGS_ATTR_ACA:
574		io->scsiio.tag_type = CTL_TAG_ACA;
575		break;
576	default:
577		io->scsiio.tag_type = CTL_TAG_UNTAGGED;
578		CFISCSI_SESSION_WARN(cs, "unhandled tag type %d",
579		    bhssc->bhssc_flags & BHSSC_FLAGS_ATTR);
580		break;
581	}
582	io->scsiio.cdb_len = sizeof(bhssc->bhssc_cdb); /* Which is 16. */
583	memcpy(io->scsiio.cdb, bhssc->bhssc_cdb, sizeof(bhssc->bhssc_cdb));
584	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
585	error = ctl_queue(io);
586	if (error != CTL_RETVAL_COMPLETE) {
587		CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d; "
588		    "dropping connection", error);
589		ctl_free_io(io);
590		refcount_release(&cs->cs_outstanding_ctl_pdus);
591		icl_pdu_free(request);
592		cfiscsi_session_terminate(cs);
593	}
594}
595
596static void
597cfiscsi_pdu_handle_task_request(struct icl_pdu *request)
598{
599	struct iscsi_bhs_task_management_request *bhstmr;
600	struct iscsi_bhs_task_management_response *bhstmr2;
601	struct icl_pdu *response;
602	struct cfiscsi_session *cs;
603	union ctl_io *io;
604	int error;
605
606	cs = PDU_SESSION(request);
607	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
608	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
609	if (io == NULL) {
610		CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io;"
611		    "dropping connection");
612		icl_pdu_free(request);
613		cfiscsi_session_terminate(cs);
614		return;
615	}
616	ctl_zero_io(io);
617	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
618	io->io_hdr.io_type = CTL_IO_TASK;
619	io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
620	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
621	io->io_hdr.nexus.targ_target.id = 0;
622	io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhstmr->bhstmr_lun);
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->lun_map = cfiscsi_lun_map;
2004	port->targ_lun_arg = ct;
2005	port->fe_datamove = cfiscsi_datamove;
2006	port->fe_done = cfiscsi_done;
2007
2008	/* XXX KDM what should we report here? */
2009	/* XXX These should probably be fetched from CTL. */
2010	port->max_targets = 1;
2011	port->max_target_id = 15;
2012
2013	port->options = opts;
2014	STAILQ_INIT(&opts);
2015
2016	/* Generate Port ID. */
2017	idlen = strlen(target) + strlen(",t,0x0001") + 1;
2018	idlen = roundup2(idlen, 4);
2019	len = sizeof(struct scsi_vpd_device_id) + idlen;
2020	port->port_devid = malloc(sizeof(struct ctl_devid) + len,
2021	    M_CTL, M_WAITOK | M_ZERO);
2022	port->port_devid->len = len;
2023	desc = (struct scsi_vpd_id_descriptor *)port->port_devid->data;
2024	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2025	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2026	    SVPD_ID_TYPE_SCSI_NAME;
2027	desc->length = idlen;
2028	snprintf(desc->identifier, idlen, "%s,t,0x%4.4x",
2029	    target, port->virtual_port);
2030
2031	/* Generate Target ID. */
2032	idlen = strlen(target) + 1;
2033	idlen = roundup2(idlen, 4);
2034	len = sizeof(struct scsi_vpd_device_id) + idlen;
2035	port->target_devid = malloc(sizeof(struct ctl_devid) + len,
2036	    M_CTL, M_WAITOK | M_ZERO);
2037	port->target_devid->len = len;
2038	desc = (struct scsi_vpd_id_descriptor *)port->target_devid->data;
2039	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2040	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2041	    SVPD_ID_TYPE_SCSI_NAME;
2042	desc->length = idlen;
2043	strlcpy(desc->identifier, target, idlen);
2044
2045	retval = ctl_port_register(port, /*master_SC*/ 1);
2046	if (retval != 0) {
2047		ctl_free_opts(&port->options);
2048		cfiscsi_target_release(ct);
2049		free(port->port_devid, M_CFISCSI);
2050		free(port->target_devid, M_CFISCSI);
2051		req->status = CTL_LUN_ERROR;
2052		snprintf(req->error_str, sizeof(req->error_str),
2053		    "ctl_frontend_register() failed with error %d", retval);
2054		return;
2055	}
2056done:
2057	ct->ct_state = CFISCSI_TARGET_STATE_ACTIVE;
2058	req->status = CTL_LUN_OK;
2059	memcpy(req->kern_args[0].kvalue, &port->targ_port,
2060	    sizeof(port->targ_port)); //XXX
2061}
2062
2063static void
2064cfiscsi_ioctl_port_remove(struct ctl_req *req)
2065{
2066	struct cfiscsi_target *ct;
2067	const char *target;
2068	ctl_options_t opts;
2069
2070	ctl_init_opts(&opts, req->num_args, req->kern_args);
2071	target = ctl_get_opt(&opts, "cfiscsi_target");
2072	if (target == NULL) {
2073		ctl_free_opts(&opts);
2074		req->status = CTL_LUN_ERROR;
2075		snprintf(req->error_str, sizeof(req->error_str),
2076		    "Missing required argument");
2077		return;
2078	}
2079	ct = cfiscsi_target_find(&cfiscsi_softc, target);
2080	if (ct == NULL) {
2081		ctl_free_opts(&opts);
2082		req->status = CTL_LUN_ERROR;
2083		snprintf(req->error_str, sizeof(req->error_str),
2084		    "can't find target \"%s\"", target);
2085		return;
2086	}
2087	if (ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE) {
2088		ctl_free_opts(&opts);
2089		req->status = CTL_LUN_ERROR;
2090		snprintf(req->error_str, sizeof(req->error_str),
2091		    "target \"%s\" is already dying", target);
2092		return;
2093	}
2094	ctl_free_opts(&opts);
2095
2096	ct->ct_state = CFISCSI_TARGET_STATE_DYING;
2097	ctl_port_offline(&ct->ct_port);
2098	cfiscsi_target_release(ct);
2099	cfiscsi_target_release(ct);
2100}
2101
2102static int
2103cfiscsi_ioctl(struct cdev *dev,
2104    u_long cmd, caddr_t addr, int flag, struct thread *td)
2105{
2106	struct ctl_iscsi *ci;
2107	struct ctl_req *req;
2108
2109	if (cmd == CTL_PORT_REQ) {
2110		req = (struct ctl_req *)addr;
2111		switch (req->reqtype) {
2112		case CTL_REQ_CREATE:
2113			cfiscsi_ioctl_port_create(req);
2114			break;
2115		case CTL_REQ_REMOVE:
2116			cfiscsi_ioctl_port_remove(req);
2117			break;
2118		default:
2119			req->status = CTL_LUN_ERROR;
2120			snprintf(req->error_str, sizeof(req->error_str),
2121			    "Unsupported request type %d", req->reqtype);
2122		}
2123		return (0);
2124	}
2125
2126	if (cmd != CTL_ISCSI)
2127		return (ENOTTY);
2128
2129	ci = (struct ctl_iscsi *)addr;
2130	switch (ci->type) {
2131	case CTL_ISCSI_HANDOFF:
2132		cfiscsi_ioctl_handoff(ci);
2133		break;
2134	case CTL_ISCSI_LIST:
2135		cfiscsi_ioctl_list(ci);
2136		break;
2137	case CTL_ISCSI_TERMINATE:
2138		cfiscsi_ioctl_terminate(ci);
2139		break;
2140	case CTL_ISCSI_LOGOUT:
2141		cfiscsi_ioctl_logout(ci);
2142		break;
2143#ifdef ICL_KERNEL_PROXY
2144	case CTL_ISCSI_LISTEN:
2145		cfiscsi_ioctl_listen(ci);
2146		break;
2147	case CTL_ISCSI_ACCEPT:
2148		cfiscsi_ioctl_accept(ci);
2149		break;
2150	case CTL_ISCSI_SEND:
2151		cfiscsi_ioctl_send(ci);
2152		break;
2153	case CTL_ISCSI_RECEIVE:
2154		cfiscsi_ioctl_receive(ci);
2155		break;
2156#else
2157	case CTL_ISCSI_LISTEN:
2158	case CTL_ISCSI_ACCEPT:
2159	case CTL_ISCSI_SEND:
2160	case CTL_ISCSI_RECEIVE:
2161		ci->status = CTL_ISCSI_ERROR;
2162		snprintf(ci->error_str, sizeof(ci->error_str),
2163		    "%s: CTL compiled without ICL_KERNEL_PROXY",
2164		    __func__);
2165		break;
2166#endif /* !ICL_KERNEL_PROXY */
2167	default:
2168		ci->status = CTL_ISCSI_ERROR;
2169		snprintf(ci->error_str, sizeof(ci->error_str),
2170		    "%s: invalid iSCSI request type %d", __func__, ci->type);
2171		break;
2172	}
2173
2174	return (0);
2175}
2176
2177static void
2178cfiscsi_target_hold(struct cfiscsi_target *ct)
2179{
2180
2181	refcount_acquire(&ct->ct_refcount);
2182}
2183
2184static void
2185cfiscsi_target_release(struct cfiscsi_target *ct)
2186{
2187	struct cfiscsi_softc *softc;
2188
2189	softc = ct->ct_softc;
2190	mtx_lock(&softc->lock);
2191	if (refcount_release(&ct->ct_refcount)) {
2192		TAILQ_REMOVE(&softc->targets, ct, ct_next);
2193		mtx_unlock(&softc->lock);
2194		if (ct->ct_state != CFISCSI_TARGET_STATE_INVALID) {
2195			ct->ct_state = CFISCSI_TARGET_STATE_INVALID;
2196			if (ctl_port_deregister(&ct->ct_port) != 0)
2197				printf("%s: ctl_port_deregister() failed\n",
2198				    __func__);
2199		}
2200		free(ct, M_CFISCSI);
2201
2202		return;
2203	}
2204	mtx_unlock(&softc->lock);
2205}
2206
2207static struct cfiscsi_target *
2208cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name)
2209{
2210	struct cfiscsi_target *ct;
2211
2212	mtx_lock(&softc->lock);
2213	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2214		if (strcmp(name, ct->ct_name) != 0 ||
2215		    ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE)
2216			continue;
2217		cfiscsi_target_hold(ct);
2218		mtx_unlock(&softc->lock);
2219		return (ct);
2220	}
2221	mtx_unlock(&softc->lock);
2222
2223	return (NULL);
2224}
2225
2226static struct cfiscsi_target *
2227cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2228    const char *alias)
2229{
2230	struct cfiscsi_target *ct, *newct;
2231	int i;
2232
2233	if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2234		return (NULL);
2235
2236	newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2237
2238	mtx_lock(&softc->lock);
2239	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2240		if (strcmp(name, ct->ct_name) != 0 ||
2241		    ct->ct_state == CFISCSI_TARGET_STATE_INVALID)
2242			continue;
2243		cfiscsi_target_hold(ct);
2244		mtx_unlock(&softc->lock);
2245		free(newct, M_CFISCSI);
2246		return (ct);
2247	}
2248
2249	for (i = 0; i < CTL_MAX_LUNS; i++)
2250		newct->ct_luns[i] = UINT32_MAX;
2251
2252	strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2253	if (alias != NULL)
2254		strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2255	refcount_init(&newct->ct_refcount, 1);
2256	newct->ct_softc = softc;
2257	TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2258	mtx_unlock(&softc->lock);
2259
2260	return (newct);
2261}
2262
2263/*
2264 * Takes LUN from the target space and returns LUN from the CTL space.
2265 */
2266static uint32_t
2267cfiscsi_lun_map(void *arg, uint32_t lun)
2268{
2269	struct cfiscsi_target *ct = arg;
2270
2271	if (lun >= CTL_MAX_LUNS) {
2272		CFISCSI_DEBUG("requested lun number %d is higher "
2273		    "than maximum %d", lun, CTL_MAX_LUNS - 1);
2274		return (UINT32_MAX);
2275	}
2276	return (ct->ct_luns[lun]);
2277}
2278
2279static int
2280cfiscsi_target_set_lun(struct cfiscsi_target *ct,
2281    unsigned long lun_id, unsigned long ctl_lun_id)
2282{
2283
2284	if (lun_id >= CTL_MAX_LUNS) {
2285		CFISCSI_WARN("requested lun number %ld is higher "
2286		    "than maximum %d", lun_id, CTL_MAX_LUNS - 1);
2287		return (-1);
2288	}
2289
2290	if (ct->ct_luns[lun_id] < CTL_MAX_LUNS) {
2291		/*
2292		 * CTL calls cfiscsi_lun_enable() twice for each LUN - once
2293		 * when the LUN is created, and a second time just before
2294		 * the port is brought online; don't emit warnings
2295		 * for that case.
2296		 */
2297		if (ct->ct_luns[lun_id] == ctl_lun_id)
2298			return (0);
2299		CFISCSI_WARN("lun %ld already allocated", lun_id);
2300		return (-1);
2301	}
2302
2303#if 0
2304	CFISCSI_DEBUG("adding mapping for lun %ld, target %s "
2305	    "to ctl lun %ld", lun_id, ct->ct_name, ctl_lun_id);
2306#endif
2307
2308	ct->ct_luns[lun_id] = ctl_lun_id;
2309
2310	return (0);
2311}
2312
2313static int
2314cfiscsi_lun_enable(void *arg, struct ctl_id target_id, int lun_id)
2315{
2316	struct cfiscsi_softc *softc;
2317	struct cfiscsi_target *ct;
2318	const char *target = NULL;
2319	const char *lun = NULL;
2320	unsigned long tmp;
2321
2322	ct = (struct cfiscsi_target *)arg;
2323	softc = ct->ct_softc;
2324
2325	target = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2326	    "cfiscsi_target");
2327	lun = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2328	    "cfiscsi_lun");
2329
2330	if (target == NULL && lun == NULL)
2331		return (0);
2332
2333	if (target == NULL || lun == NULL) {
2334		CFISCSI_WARN("lun added with cfiscsi_target, but without "
2335		    "cfiscsi_lun, or the other way around; ignoring");
2336		return (0);
2337	}
2338
2339	if (strcmp(target, ct->ct_name) != 0)
2340		return (0);
2341
2342	tmp = strtoul(lun, NULL, 10);
2343	cfiscsi_target_set_lun(ct, tmp, lun_id);
2344	return (0);
2345}
2346
2347static int
2348cfiscsi_lun_disable(void *arg, struct ctl_id target_id, int lun_id)
2349{
2350	struct cfiscsi_softc *softc;
2351	struct cfiscsi_target *ct;
2352	int i;
2353
2354	ct = (struct cfiscsi_target *)arg;
2355	softc = ct->ct_softc;
2356
2357	mtx_lock(&softc->lock);
2358	for (i = 0; i < CTL_MAX_LUNS; i++) {
2359		if (ct->ct_luns[i] != lun_id)
2360			continue;
2361		ct->ct_luns[i] = UINT32_MAX;
2362		break;
2363	}
2364	mtx_unlock(&softc->lock);
2365	return (0);
2366}
2367
2368static void
2369cfiscsi_datamove_in(union ctl_io *io)
2370{
2371	struct cfiscsi_session *cs;
2372	struct icl_pdu *request, *response;
2373	const struct iscsi_bhs_scsi_command *bhssc;
2374	struct iscsi_bhs_data_in *bhsdi;
2375	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2376	size_t len, expected_len, sg_len, buffer_offset;
2377	const char *sg_addr;
2378	int ctl_sg_count, error, i;
2379
2380	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2381	cs = PDU_SESSION(request);
2382
2383	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2384	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2385	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2386	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2387
2388	if (io->scsiio.kern_sg_entries > 0) {
2389		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2390		ctl_sg_count = io->scsiio.kern_sg_entries;
2391	} else {
2392		ctl_sglist = &ctl_sg_entry;
2393		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2394		ctl_sglist->len = io->scsiio.kern_data_len;
2395		ctl_sg_count = 1;
2396	}
2397
2398	/*
2399	 * This is the total amount of data to be transferred within the current
2400	 * SCSI command.  We need to record it so that we can properly report
2401	 * underflow/underflow.
2402	 */
2403	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2404
2405	/*
2406	 * This is the offset within the current SCSI command; for the first
2407	 * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2408	 * it will be the sum of lengths of previous ones.
2409	 */
2410	buffer_offset = io->scsiio.kern_rel_offset;
2411
2412	/*
2413	 * This is the transfer length expected by the initiator.  In theory,
2414	 * it could be different from the correct amount of data from the SCSI
2415	 * point of view, even if that doesn't make any sense.
2416	 */
2417	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2418#if 0
2419	if (expected_len != io->scsiio.kern_total_len) {
2420		CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2421		    "actual length %zd", expected_len,
2422		    (size_t)io->scsiio.kern_total_len);
2423	}
2424#endif
2425
2426	if (buffer_offset >= expected_len) {
2427#if 0
2428		CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2429		    "already sent the expected len", buffer_offset);
2430#endif
2431		io->scsiio.be_move_done(io);
2432		return;
2433	}
2434
2435	i = 0;
2436	sg_addr = NULL;
2437	sg_len = 0;
2438	response = NULL;
2439	bhsdi = NULL;
2440	for (;;) {
2441		if (response == NULL) {
2442			response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2443			if (response == NULL) {
2444				CFISCSI_SESSION_WARN(cs, "failed to "
2445				    "allocate memory; dropping connection");
2446				ctl_set_busy(&io->scsiio);
2447				io->scsiio.be_move_done(io);
2448				cfiscsi_session_terminate(cs);
2449				return;
2450			}
2451			bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2452			bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2453			bhsdi->bhsdi_initiator_task_tag =
2454			    bhssc->bhssc_initiator_task_tag;
2455			bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2456			PDU_EXPDATASN(request)++;
2457			bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2458		}
2459
2460		KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2461		if (sg_len == 0) {
2462			sg_addr = ctl_sglist[i].addr;
2463			sg_len = ctl_sglist[i].len;
2464			KASSERT(sg_len > 0, ("sg_len <= 0"));
2465		}
2466
2467		len = sg_len;
2468
2469		/*
2470		 * Truncate to maximum data segment length.
2471		 */
2472		KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2473		    ("ip_data_len %zd >= max_data_segment_length %zd",
2474		    response->ip_data_len, cs->cs_max_data_segment_length));
2475		if (response->ip_data_len + len >
2476		    cs->cs_max_data_segment_length) {
2477			len = cs->cs_max_data_segment_length -
2478			    response->ip_data_len;
2479			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2480			    len, sg_len));
2481		}
2482
2483		/*
2484		 * Truncate to expected data transfer length.
2485		 */
2486		KASSERT(buffer_offset + response->ip_data_len < expected_len,
2487		    ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2488		    buffer_offset, response->ip_data_len, expected_len));
2489		if (buffer_offset + response->ip_data_len + len > expected_len) {
2490			CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2491			    "to expected data transfer length %zd",
2492			    buffer_offset + response->ip_data_len + len, expected_len);
2493			len = expected_len - (buffer_offset + response->ip_data_len);
2494			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2495			    len, sg_len));
2496		}
2497
2498		error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2499		if (error != 0) {
2500			CFISCSI_SESSION_WARN(cs, "failed to "
2501			    "allocate memory; dropping connection");
2502			icl_pdu_free(response);
2503			ctl_set_busy(&io->scsiio);
2504			io->scsiio.be_move_done(io);
2505			cfiscsi_session_terminate(cs);
2506			return;
2507		}
2508		sg_addr += len;
2509		sg_len -= len;
2510
2511		KASSERT(buffer_offset + request->ip_data_len <= expected_len,
2512		    ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2513		    buffer_offset, request->ip_data_len, expected_len));
2514		if (buffer_offset + request->ip_data_len == expected_len) {
2515			/*
2516			 * Already have the amount of data the initiator wanted.
2517			 */
2518			break;
2519		}
2520
2521		if (sg_len == 0) {
2522			/*
2523			 * End of scatter-gather segment;
2524			 * proceed to the next one...
2525			 */
2526			if (i == ctl_sg_count - 1) {
2527				/*
2528				 * ... unless this was the last one.
2529				 */
2530				break;
2531			}
2532			i++;
2533		}
2534
2535		if (response->ip_data_len == cs->cs_max_data_segment_length) {
2536			/*
2537			 * Can't stuff more data into the current PDU;
2538			 * queue it.  Note that's not enough to check
2539			 * for kern_data_resid == 0 instead; there
2540			 * may be several Data-In PDUs for the final
2541			 * call to cfiscsi_datamove(), and we want
2542			 * to set the F flag only on the last of them.
2543			 */
2544			buffer_offset += response->ip_data_len;
2545			if (buffer_offset == io->scsiio.kern_total_len ||
2546			    buffer_offset == expected_len)
2547				bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2548			cfiscsi_pdu_queue(response);
2549			response = NULL;
2550			bhsdi = NULL;
2551		}
2552	}
2553	if (response != NULL) {
2554		buffer_offset += response->ip_data_len;
2555		if (buffer_offset == io->scsiio.kern_total_len ||
2556		    buffer_offset == expected_len)
2557			bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2558		KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2559		cfiscsi_pdu_queue(response);
2560	}
2561
2562	io->scsiio.be_move_done(io);
2563}
2564
2565static void
2566cfiscsi_datamove_out(union ctl_io *io)
2567{
2568	struct cfiscsi_session *cs;
2569	struct icl_pdu *request, *response;
2570	const struct iscsi_bhs_scsi_command *bhssc;
2571	struct iscsi_bhs_r2t *bhsr2t;
2572	struct cfiscsi_data_wait *cdw;
2573	uint32_t target_transfer_tag;
2574	bool done;
2575
2576	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2577	cs = PDU_SESSION(request);
2578
2579	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2580	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2581	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2582	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2583
2584	/*
2585	 * We need to record it so that we can properly report
2586	 * underflow/underflow.
2587	 */
2588	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2589
2590	/*
2591	 * We hadn't received anything during this datamove yet.
2592	 */
2593	io->scsiio.ext_data_filled = 0;
2594
2595	target_transfer_tag =
2596	    atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2597
2598#if 0
2599	CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2600	    "task tag 0x%x, target transfer tag 0x%x",
2601	    bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2602#endif
2603	cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
2604	if (cdw == NULL) {
2605		CFISCSI_SESSION_WARN(cs, "failed to "
2606		    "allocate memory; dropping connection");
2607		ctl_set_busy(&io->scsiio);
2608		io->scsiio.be_move_done(io);
2609		cfiscsi_session_terminate(cs);
2610		return;
2611	}
2612	cdw->cdw_ctl_io = io;
2613	cdw->cdw_target_transfer_tag = target_transfer_tag;
2614	cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2615
2616	if (cs->cs_immediate_data && io->scsiio.kern_rel_offset <
2617	    icl_pdu_data_segment_length(request)) {
2618		done = cfiscsi_handle_data_segment(request, cdw);
2619		if (done) {
2620			uma_zfree(cfiscsi_data_wait_zone, cdw);
2621			io->scsiio.be_move_done(io);
2622			return;
2623		}
2624	}
2625
2626	CFISCSI_SESSION_LOCK(cs);
2627	TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2628	CFISCSI_SESSION_UNLOCK(cs);
2629
2630	/*
2631	 * XXX: We should limit the number of outstanding R2T PDUs
2632	 * 	per task to MaxOutstandingR2T.
2633	 */
2634	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2635	if (response == NULL) {
2636		CFISCSI_SESSION_WARN(cs, "failed to "
2637		    "allocate memory; dropping connection");
2638		ctl_set_busy(&io->scsiio);
2639		io->scsiio.be_move_done(io);
2640		cfiscsi_session_terminate(cs);
2641		return;
2642	}
2643	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2644	bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2645	bhsr2t->bhsr2t_flags = 0x80;
2646	bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2647	bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2648	bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2649	/*
2650	 * XXX: Here we assume that cfiscsi_datamove() won't ever
2651	 *	be running concurrently on several CPUs for a given
2652	 *	command.
2653	 */
2654	bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2655	PDU_R2TSN(request)++;
2656	/*
2657	 * This is the offset within the current SCSI command;
2658	 * i.e. for the first call of datamove(), it will be 0,
2659	 * and for subsequent ones it will be the sum of lengths
2660	 * of previous ones.
2661	 *
2662	 * The ext_data_filled is to account for unsolicited
2663	 * (immediate) data that might have already arrived.
2664	 */
2665	bhsr2t->bhsr2t_buffer_offset =
2666	    htonl(io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled);
2667	/*
2668	 * This is the total length (sum of S/G lengths) this call
2669	 * to cfiscsi_datamove() is supposed to handle.
2670	 *
2671	 * XXX: Limit it to MaxBurstLength.
2672	 */
2673	bhsr2t->bhsr2t_desired_data_transfer_length =
2674	    htonl(io->scsiio.kern_data_len - io->scsiio.ext_data_filled);
2675	cfiscsi_pdu_queue(response);
2676}
2677
2678static void
2679cfiscsi_datamove(union ctl_io *io)
2680{
2681
2682	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2683		cfiscsi_datamove_in(io);
2684	else
2685		cfiscsi_datamove_out(io);
2686}
2687
2688static void
2689cfiscsi_scsi_command_done(union ctl_io *io)
2690{
2691	struct icl_pdu *request, *response;
2692	struct iscsi_bhs_scsi_command *bhssc;
2693	struct iscsi_bhs_scsi_response *bhssr;
2694#ifdef DIAGNOSTIC
2695	struct cfiscsi_data_wait *cdw;
2696#endif
2697	struct cfiscsi_session *cs;
2698	uint16_t sense_length;
2699
2700	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2701	cs = PDU_SESSION(request);
2702	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2703	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2704	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2705	    ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2706
2707	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2708	//    bhssc->bhssc_initiator_task_tag);
2709
2710#ifdef DIAGNOSTIC
2711	CFISCSI_SESSION_LOCK(cs);
2712	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2713		KASSERT(bhssc->bhssc_initiator_task_tag !=
2714		    cdw->cdw_initiator_task_tag, ("dangling cdw"));
2715	CFISCSI_SESSION_UNLOCK(cs);
2716#endif
2717
2718	/*
2719	 * Do not return status for aborted commands.
2720	 * There are exceptions, but none supported by CTL yet.
2721	 */
2722	if (io->io_hdr.status == CTL_CMD_ABORTED) {
2723		ctl_free_io(io);
2724		icl_pdu_free(request);
2725		return;
2726	}
2727
2728	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2729	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2730	bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2731	bhssr->bhssr_flags = 0x80;
2732	/*
2733	 * XXX: We don't deal with bidirectional under/overflows;
2734	 *	does anything actually support those?
2735	 */
2736	if (PDU_TOTAL_TRANSFER_LEN(request) <
2737	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2738		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2739		bhssr->bhssr_residual_count =
2740		    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2741		    PDU_TOTAL_TRANSFER_LEN(request));
2742		//CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2743		//    ntohl(bhssr->bhssr_residual_count));
2744	} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2745	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2746		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2747		bhssr->bhssr_residual_count =
2748		    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2749		    ntohl(bhssc->bhssc_expected_data_transfer_length));
2750		//CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2751		//    ntohl(bhssr->bhssr_residual_count));
2752	}
2753	bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2754	bhssr->bhssr_status = io->scsiio.scsi_status;
2755	bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2756	bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2757
2758	if (io->scsiio.sense_len > 0) {
2759#if 0
2760		CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2761		    io->scsiio.sense_len);
2762#endif
2763		sense_length = htons(io->scsiio.sense_len);
2764		icl_pdu_append_data(response,
2765		    &sense_length, sizeof(sense_length), M_WAITOK);
2766		icl_pdu_append_data(response,
2767		    &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2768	}
2769
2770	ctl_free_io(io);
2771	icl_pdu_free(request);
2772	cfiscsi_pdu_queue(response);
2773}
2774
2775static void
2776cfiscsi_task_management_done(union ctl_io *io)
2777{
2778	struct icl_pdu *request, *response;
2779	struct iscsi_bhs_task_management_request *bhstmr;
2780	struct iscsi_bhs_task_management_response *bhstmr2;
2781	struct cfiscsi_data_wait *cdw, *tmpcdw;
2782	struct cfiscsi_session *cs;
2783
2784	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2785	cs = PDU_SESSION(request);
2786	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2787	KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2788	    ISCSI_BHS_OPCODE_TASK_REQUEST,
2789	    ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2790
2791#if 0
2792	CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2793	    bhstmr->bhstmr_initiator_task_tag,
2794	    bhstmr->bhstmr_referenced_task_tag);
2795#endif
2796
2797	if ((bhstmr->bhstmr_function & ~0x80) ==
2798	    BHSTMR_FUNCTION_ABORT_TASK) {
2799		/*
2800		 * Make sure we no longer wait for Data-Out for this command.
2801		 */
2802		CFISCSI_SESSION_LOCK(cs);
2803		TAILQ_FOREACH_SAFE(cdw,
2804		    &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2805			if (bhstmr->bhstmr_referenced_task_tag !=
2806			    cdw->cdw_initiator_task_tag)
2807				continue;
2808
2809#if 0
2810			CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2811			    "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2812#endif
2813			TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2814			    cdw, cdw_next);
2815			cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2816			uma_zfree(cfiscsi_data_wait_zone, cdw);
2817		}
2818		CFISCSI_SESSION_UNLOCK(cs);
2819	}
2820
2821	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2822	bhstmr2 = (struct iscsi_bhs_task_management_response *)
2823	    response->ip_bhs;
2824	bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2825	bhstmr2->bhstmr_flags = 0x80;
2826	if (io->io_hdr.status == CTL_SUCCESS) {
2827		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2828	} else {
2829		/*
2830		 * XXX: How to figure out what exactly went wrong?  iSCSI spec
2831		 * 	expects us to provide detailed error, e.g. "Task does
2832		 * 	not exist" or "LUN does not exist".
2833		 */
2834		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2835		bhstmr2->bhstmr_response =
2836		    BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2837	}
2838	bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2839
2840	ctl_free_io(io);
2841	icl_pdu_free(request);
2842	cfiscsi_pdu_queue(response);
2843}
2844
2845static void
2846cfiscsi_done(union ctl_io *io)
2847{
2848	struct icl_pdu *request;
2849	struct cfiscsi_session *cs;
2850
2851	KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2852		("invalid CTL status %#x", io->io_hdr.status));
2853
2854	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2855	if (request == NULL) {
2856		/*
2857		 * Implicit task termination has just completed; nothing to do.
2858		 */
2859		return;
2860	}
2861
2862	cs = PDU_SESSION(request);
2863	refcount_release(&cs->cs_outstanding_ctl_pdus);
2864
2865	switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2866	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2867		cfiscsi_scsi_command_done(io);
2868		break;
2869	case ISCSI_BHS_OPCODE_TASK_REQUEST:
2870		cfiscsi_task_management_done(io);
2871		break;
2872	default:
2873		panic("cfiscsi_done called with wrong opcode 0x%x",
2874		    request->ip_bhs->bhs_opcode);
2875	}
2876}
2877